pythonpython-itertoolscombinatoricsmore-itertools

How to introduce constraints using Python itertools.product()?


The following script generates 4-character permutations of set s and outputs to file:

import itertools


s = ['1', '2', '3', '4', '!']

l = list(itertools.product(s, repeat=4))

with open('output1.txt', 'w') as f:
    for i in l:
        f.write(''.join([str(v) for v in i]) + '\n')

Output:

...
11!1
11!2
11!3
11!4
11!!
...

How are constraints introduced such as:


Solution

  • The repeat parameter is meant to be used when you do want the same set of options for each position in the sequence. Since you don't, then you should just use positional arguments to give the options for each position in the sequence. (docs link)

    For your example, the first letter can be any of ['1', '2', '3', '4'], and the third letter can only be '3':

    import itertools as it
    
    s = ['1', '2', '3', '4', '!']
    no_exclamation_mark = ['1', '2', '3', '4']
    only_3 = ['3']
    
    l = it.product(no_exclamation_mark, s, only_3, s)
    

    @Kelly Bundy wrote the same solution in a comment, but simplified using the fact that strings are sequences of characters, so if your options for each position are just one character each then you don't need to put them in lists:

    l = it.product('1234', '1234!', '3', '1234!')