enumeration of character sequence "permutations" (python)

Viewed 25

I have following problem:

There are n=20 characters in the sequence. For each position there is a predefined list of possible characters which can be 1 to m (where m usually is a single digit).

How can I enumerate all possible permutations efficiently? Or in essence is there some preexisting library (numpy?) that could do that before I try it myself?

1 Answers

itertools.product seems to offer what I need. I just need to pass it a list of list:

itertools.product(*positions)

where positions is a list of lists (eg which chars at which positions).

In my case the available options for each position are small and often also just 1 so that keeps the number of possibilities in check but might crash your application if too many get generated.

I then build the final string:

for s in itertools.product(*positions):
    result = ''.join(s) 
    results.append(result)
Related