Reputation: 67
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 create a script that can take a string input containing query marks (like AB?D?) and a set of options (ABC, DEF) to output all of the possible combinations, like below.
ABADD, ABADE, ABADF
ABBDD, ABBDE, ABBDF
ABCDD, ABCDE, ABCDF
In searching, I also found this but I'm not entirely sure how I might be able to implement this around my input.
Would it be most efficient to break down the input string into multiple substrings around the question marks (so the above example becomes AB + ? + D + ?). Would something like list (s) be suitable for this?
Thanks in advance for any help offered.
Upvotes: 1
Views: 827
Reputation: 82889
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.)
def combine(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']
Upvotes: 4