Skip to content Skip to sidebar Skip to footer

Generate Combinations From An Input In Python

I'm not sure how to go about this in Python. In searching for this, I have come across itertools but I'm not sure how I might apply it in this case. What I am trying to do is creat

Solution 1:

You can use itertools.product to get the combinations and string.format to merge those into the template string. (First, replace the ? with {} to get format string syntax.)

defcombine(template, options):
    template = template.replace('?', '{}')
    for opts in itertools.product(*options):
        yield template.format(*opts)

Example:

>>> list(combine('AB?D?', ['ABC', 'DEF']))
['ABADD', 'ABADE', 'ABADF', 'ABBDD', 'ABBDE', 'ABBDF', 'ABCDD', 'ABCDE', 'ABCDF']

Post a Comment for "Generate Combinations From An Input In Python"