Reputation: 160
I have all possible combinations of operations between numbers in a list:
list = ['2','7','8']
7+8*2
8+7*2
2*8+7
2+8*7
2-8*7
8-2/7
etc
I want to know if it's possible to say that operations like ('7*2+8' and '8+7*2' and '2*7+8') or (7*8*2 and 2*8*7 and 7*2*8) etc. are the same. I want to know how take only one operation if it's the same operation.
This is my code to create these different operations:
Op = ['+','-','*','/']
array = []
for i in Op:
array.append(string1 + i + string2)
return array
Upvotes: 3
Views: 90
Reputation: 1032
if I understand you well, I think I have an idea for you.
First of all, you need to create all of the possible permutations of digits and expressions. You can do that in this way:
import itertools
num_list = ['2','7','8']
op = ['+','-','*','/'] * 2 # *2 for the case of same operator twice
num_perm = list(itertools.permutations(num_list))
op_perm = list(itertools.permutations(op, 2)) # We want perm of two operators.
Now, you need to merge all the permutation to a math expression, this is a nice way for that:
list_of_experssions = list()
for num in num_perm :
for op in op_perm:
list_of_experssions.append(num[0] + op[0] + num[1] + op[1] +num[2])
The last step is to check if the results of the two expressions are equal (using eval
function) but the expressions themself are different:
for exp1 in list_of_experssions:
for exp2 in list_of_experssions:
if eval(exp1) == eval(exp2) and exp1 != exp2:
print(exp1, exp2)
In your case, we got 336 math expressions and 2560 couples of equal expressions.
Upvotes: 2