Home > Blockchain >  Getting all the possible combinations of values
Getting all the possible combinations of values

Time:09-28

I want to write a code that shows all the possibilities of outputs. the code below shows the combinations with variables that have no repetition so for the iteration of 2 it does not include ('yes', 'yes') or ('no', 'no'). I want to add repeatable values in the expected output. The iterator value specifies how many combinations there are and they must all be the same length 2 or 3. How will I be able to do that and get the expected output for iterations of 2 and 3?

# the possible combinations
  
from itertools import permutations

def vals(iterator):
    # of length 2
    comb = permutations(['yes','no'], iterator)
    print(f"iter amount :{iterator}")
    for i in comb:
        print(i)
    
vals(2)
vals(3)

Outputs:

iter amount :2
('yes', 'no')
('no', 'yes')
iter amount :3

Expected Outputs:

iter amount :2
('yes', 'yes')
('yes', 'no')
('no', 'yes')
('no', 'no')
iter amount :3
('yes', 'yes', 'yes')
('yes', 'yes', 'no')
('yes', 'no', 'no')
('no', 'no', 'no')
('no', 'no', 'yes')
('no', 'yes', 'yes')

CodePudding user response:

Looks like you may be looking for itertools.product instead.

>>> import itertools
>>> for x in itertools.product(('yes', 'no'), repeat=3):
...     print(x)
...
('yes', 'yes', 'yes')
('yes', 'yes', 'no')
('yes', 'no', 'yes')
('yes', 'no', 'no')
('no', 'yes', 'yes')
('no', 'yes', 'no')
('no', 'no', 'yes')
('no', 'no', 'no')
  • Related