3

I need to create all possible sequences of three arithmetic operators (+, -, *, /).

For list operators = ['+', '-', '*', '/'], i have tried using list(itertools.combinations_with_replacement(operators ,3)), which returns this list:

[('+', '+', '+'), ('+', '+', '-'), ('+', '+', '/'), ('+', '+', '*'), ('+', '-', '-'), ('+', '-', '/'), ('+', '-', '*'), ('+', '/', '/'), ('+', '/', '*'), ('+', '*', '*'), ('-', '-', '-'), ('-', '-', '/'), ('-', '-', '*'), ('-', '/', '/'), ('-', '/', '*'), ('-', '*', '*'), ('/', '/', '/'), ('/', '/', '*'), ('/', '*', '*'), ('*', '*', '*')]

The problem is that I also need combinations like ('*', '+', '*'), which are not included. I have also tried itertools.permutations(operators, 3), but in this case, operators won't be repeated.

How can I get all the desired results?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
SevO
  • 303
  • 2
  • 11

1 Answers1

5

That's what itertools.product is for:

from itertools import product

result = list(product(operators,repeat=3))

This constructs:

>>> list(product(operators,repeat=3))
[('+', '+', '+'), ('+', '+', '-'), ('+', '+', '*'), ('+', '+', '/'), ('+', '-', '+'), ('+', '-', '-'), ('+', '-', '*'), ('+', '-', '/'), ('+', '*', '+'), ('+', '*', '-'), ('+', '*', '*'), ('+', '*', '/'), ('+', '/', '+'), ('+', '/', '-'), ('+', '/', '*'), ('+', '/', '/'), ('-', '+', '+'), ('-', '+', '-'), ('-', '+', '*'), ('-', '+', '/'), ('-', '-', '+'), ('-', '-', '-'), ('-', '-', '*'), ('-', '-', '/'), ('-', '*', '+'), ('-', '*', '-'), ('-', '*', '*'), ('-', '*', '/'), ('-', '/', '+'), ('-', '/', '-'), ('-', '/', '*'), ('-', '/', '/'), ('*', '+', '+'), ('*', '+', '-'), ('*', '+', '*'), ('*', '+', '/'), ('*', '-', '+'), ('*', '-', '-'), ('*', '-', '*'), ('*', '-', '/'), ('*', '*', '+'), ('*', '*', '-'), ('*', '*', '*'), ('*', '*', '/'), ('*', '/', '+'), ('*', '/', '-'), ('*', '/', '*'), ('*', '/', '/'), ('/', '+', '+'), ('/', '+', '-'), ('/', '+', '*'), ('/', '+', '/'), ('/', '-', '+'), ('/', '-', '-'), ('/', '-', '*'), ('/', '-', '/'), ('/', '*', '+'), ('/', '*', '-'), ('/', '*', '*'), ('/', '*', '/'), ('/', '/', '+'), ('/', '/', '-'), ('/', '/', '*'), ('/', '/', '/')]
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
  • I have tried, but it did nothing so i stopped the process because i thought there is some fault which caused infinite loop. Now i know it only takes some time. Thank you! – SevO Apr 13 '17 at 11:03
  • @SevO That only takes a few microseconds, you must be quite impatient :-) – Stefan Pochmann Apr 13 '17 at 11:05
  • @SevO: this actually runs in milliseconds. Of course if you increas `repeat` then the number of items blows up exponentially. So from the moment `repeat` is like 12 or more, it will indeed take a long time. – Willem Van Onsem Apr 13 '17 at 11:09
  • Well, i tried it in IDLE at first and it stopped, that's why i was confused :) Thank you all for answers! – SevO Apr 13 '17 at 18:28