Search code examples
pythonstringpython-itertools

Python: create all derivatives of string by replacing its symbols


I've got some dict like that

d = {'a' : ['1', '+', '='], 'b' : ['2'], c : ['3']}

My goal is to create a list of all possible derivatives from initial word by replacing its elements like that:

word = 'abcde'
rez = ['abcde', 
       '1bcde', '+bcde', '=bcde', 
       'a2cde', '12cde', '+2cde', '=2cde', 
       'ab3de', '1b3de', '+b3de', '=b3de', 'a23de', '123de', '+23de', '=23de']

Order of words in rez is not important.

I feel that there should be some easy way with itertools, but I can't see it. Any nice and beautiful solution would be very welcome.


Solution

  • Sure, itertools is always the answer for these kind of problems. There may be better alternatives but the first that comes to my mind is using itertools.product:

    from itertools import product
    
    [''.join(chars) for chars in product(*[[x] + d.get(x, []) for x in word])]
    

    Output

    ['abcde', 'ab3de', 'a2cde', 'a23de', '1bcde', '1b3de', '12cde', '123de',
     '+bcde', '+b3de', '+2cde', '+23de', '=bcde', '=b3de', '=2cde', '=23de']