Combinations of items in a list in Python 3.x

I am currently working on a project where I need to find the correct combination of a number using arithmetic operators (+, -, *, /) and I need to create all possible combinations of elements in a list of 4 operators.
For a list, operators = ['+', '-', '*', '/']

I tried to use list(itertools.combinations_with_replacement(operators ,3))

, but it returns a list:

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

      

The problem is that I also need combinations like ('*', '+', '*')

that are not included.
I also tried itertools.permutations(operators, 3)

, but in this case the statements are not repeated.

Is there a way or method how I can get all the possible combinations?
Thank.

+3


source to share


1 answer


What's that itertools.product

for:

from itertools import product

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



This construct:

>>> list(product(operators,repeat=3))
[('+', '+', '+'), ('+', '+', '-'), ('+', '+', '*'), ('+', '+', '/'), ('+', '-', '+'), ('+', '-', '-'), ('+', '-', '*'), ('+', '-', '/'), ('+', '*', '+'), ('+', '*', '-'), ('+', '*', '*'), ('+', '*', '/'), ('+', '/', '+'), ('+', '/', '-'), ('+', '/', '*'), ('+', '/', '/'), ('-', '+', '+'), ('-', '+', '-'), ('-', '+', '*'), ('-', '+', '/'), ('-', '-', '+'), ('-', '-', '-'), ('-', '-', '*'), ('-', '-', '/'), ('-', '*', '+'), ('-', '*', '-'), ('-', '*', '*'), ('-', '*', '/'), ('-', '/', '+'), ('-', '/', '-'), ('-', '/', '*'), ('-', '/', '/'), ('*', '+', '+'), ('*', '+', '-'), ('*', '+', '*'), ('*', '+', '/'), ('*', '-', '+'), ('*', '-', '-'), ('*', '-', '*'), ('*', '-', '/'), ('*', '*', '+'), ('*', '*', '-'), ('*', '*', '*'), ('*', '*', '/'), ('*', '/', '+'), ('*', '/', '-'), ('*', '/', '*'), ('*', '/', '/'), ('/', '+', '+'), ('/', '+', '-'), ('/', '+', '*'), ('/', '+', '/'), ('/', '-', '+'), ('/', '-', '-'), ('/', '-', '*'), ('/', '-', '/'), ('/', '*', '+'), ('/', '*', '-'), ('/', '*', '*'), ('/', '*', '/'), ('/', '/', '+'), ('/', '/', '-'), ('/', '/', '*'), ('/', '/', '/')]
      

+5


source







All Articles