3

I've got a template of equations template = (a op b) op c where the available operations op are the following: op = ['+', '-', '/', '*'].

What I want to do is to compute all the possible combinations of this equation using the operations op and the parameters a, b and c.

e.g.

(a + b) + c
(a - b) - c
(a * b) * c
(a / b) / c
(a + c) + b
(a - c) + b
(b * a) - c
...
...
...

I had a look at itertools.combinations however I am not quite sure if (or how) I can use this function in this particular context.

Giorgos Myrianthous
  • 36,235
  • 20
  • 134
  • 156
  • put your code, what you have tried yet. That will clear more – Sanket Jun 21 '17 at 11:50
  • 1
    Build all the possibilities by using string concatenation, then parse one by one. See https://stackoverflow.com/questions/2371436/evaluating-a-mathematical-expression-in-a-string – Bathsheba Jun 21 '17 at 11:52
  • 1
    You want the *cartesian product* of your operators, not the combinations. `itertools.product(op, repeat=2)` generates those. – Martijn Pieters Jun 21 '17 at 11:55

2 Answers2

3

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])
elixenide
  • 44,308
  • 16
  • 74
  • 100
fafl
  • 7,222
  • 3
  • 27
  • 50
1

You need three things here:

  • The permutations of your three variable: (a,b,c), (a,c,b), (b,c,a), etc.
  • The cartesian product of your operation set with itself: (*, -), (-, +), (+, -), (+, +), etc.
  • The cartesian product between the variables permutations 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]))
NiziL
  • 5,068
  • 23
  • 33