How to generate all permutations of a list but also add strings that can be present only once in any permutation

99 Views Asked by At

itertools.product is very convenient to generate all permutations of a list, but how would one proceed to implicate another list of elements where only one element of that list could populate any permutation at a time ?

In pseudocode :

from itertools import product
product('ABC', repeat=1) + ['.', '%3A']
->A, B, C, .A, .B, .C, A., B., C., %3AA, %3AB, %3AC, A%3A, B%3A, C%3A

I suppose it would be non trivial and one would have to tweak the permutation building algorithm.

1

There are 1 best solutions below

3
On BEST ANSWER

You have 3 series. The original input string as a list, and then you prepend and append. Generate those three separately:

from itertools import chain, product

inputstring = 'ABC'
extra = ['.', '%3A']
for combo in chain(inputstring, 
        product(extra, inputstring), product(inputstring, extra)):
    combo = ''.join(combo)
    print(combo)

Demo with a list comprehension:

>>> from itertools import chain, product
>>> inputstring = 'ABC'
>>> extra = ['.', '%3A']
>>> [''.join(combo) for combo in chain(inputstring, product(extra, inputstring), product(inputstring, extra))]
['A', 'B', 'C', '.A', '.B', '.C', '%3AA', '%3AB', '%3AC', 'A.', 'A%3A', 'B.', 'B%3A', 'C.', 'C%3A']