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.

+3


source to share


2 answers


This does what you want:



import itertools

symbol = ['a', 'b', 'c']
op = ['+', '-', '/', '*']

for symbols in itertools.permutations(symbol):
    for ops in itertools.product(op, repeat=2):
        print "(%s %s %s) %s %s" % (
            symbols[0], ops[0], symbols[1], ops[1], symbols[2])

      

+3


source


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]))

      

+1


source







All Articles