Combined string combinations

So I have a string '1xxx1' and I want to replace a certain number (maybe everything, maybe not) x with a character, let's say "5". I want all possible combinations (... there can be permutations) of a string where x is either substituted or remains as x. I would like these results to be stored in a list.

So the desired output would be

>>> myList = GenerateCombinations('1xxx1', '5')
>>> print myList
['1xxx1','15xx1','155x1','15551','1x5x1','1x551','1xx51']

      

Obviously, I would like it to be able to handle strings of any length with any number of x, and also be able to replace any number. I've tried using loops and recursion to figure it out to no avail. Any help would be appreciated.

+3


source to share


1 answer


What about:

from itertools import product

def filler(word, from_char, to_char):
    options = [(c,) if c != from_char else (from_char, to_char) for c in word]
    return (''.join(o) for o in product(*options))

      

which gives

>>> filler("1xxx1", "x", "5")
<generator object <genexpr> at 0x8fa798c>
>>> list(filler("1xxx1", "x", "5"))
['1xxx1', '1xx51', '1x5x1', '1x551', '15xx1', '15x51', '155x1', '15551']

      



(Note that you're missing 15x51

.) Basically, we first list all the possible targets for each letter in the original word:

>>> word = '1xxx1'
>>> from_char = 'x'
>>> to_char = '5'
>>> [(c,) if c != from_char else (from_char, to_char) for c in word]
[('1',), ('x', '5'), ('x', '5'), ('x', '5'), ('1',)]

      

And then we use itertools.product

to get the Cartesian product of these possibilities and combine the results together.

For bonus points, change to accept substitution dictionary.: ^)

+11


source







All Articles