Calculate possible combinations of an equation
I have a template of equations template = (a op b) op c
where the available operations op
are as follows: op = ['+', '-', '/', '*']
.
What I want to do is calculate all possible combinations of this equation using the operations op
and parameters a
, b
and c
.
eg.
(a + b) + c
(a - b) - c
(a * b) * c
(a / b) / c
(a + c) + b
(a - c) + b
(b * a) - c
...
...
...
I've looked at itertools.combinations
, but I'm not entirely sure what (or how) I can use this feature in this particular context.
source to share
You need three things:
- Permutations of three variables: (a, b, c), (a, c, b), (b, c, a), etc.
- The Cartesian product of your operation is specified with itself: (*, -), (-, +), (+, -), (+, +), etc.
- Cartesian product between permutations of variables and the previous product.
So, using the glorious itertools
:
import itertools as it
vars = 'abc'
ops = '+-/*'
vars_permutations = it.permutations(vars)
op_permutations = it.product(ops, repeat=2)
for var, op in it.product(vars_permutations, op_permutations):
print('({} {} {}) {} {}'.format(var[0], op[0], var[1], op[1], var[2]))
source to share