I\'m looking to write a short script that will allow me to generate all possible letter combinations with the parameters I set.
For example:
_ _ b _ a
P
I would approach this as follows, using itertools.product in a generator function (to avoid building the whole list unless you absolutely have to):
from itertools import product
def words(definition):
for t in product(*definition):
yield "".join(t)
The only trick is providing the definition
in an appropriate format; it must be a list of iterables, each of which provides the options for each "letter". This is easy where each option for a letter is a single character:
>>> list(words(["f", "o", "aeiou"]))
['foa', 'foe', 'foi', 'foo', 'fou']
But with your multiple-character letters you will need to supply a list or tuple:
>>> list(words([['ph', 'sd', 'nn', 'mm', 'gh'],
['a', 'e', 'i', 'o', 'u', 'y', 'rc'],
'b',
['a', 'e', 'i', 'o', 'u', 'y', 'rc'],
'a']))
['phabaa', 'phabea', 'phabia', ..., 'ghrcbya', 'ghrcbrca']
Note that in Python 3.3 onwards, this can be done in a single line with yield from:
def words(definition):
yield from map("".join, product(*definition))