1

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.

2
  • Are ABC and DEF fixed to the positions of the corresponding ?s? Also even though you are not sure of the approach, you should probably share code that you have tried. Commented Oct 11, 2015 at 12:45
  • I think this is a simple string replace problem with a for loop so I can write necessary code but you should wait for a while. tutorialspoint.com/python/string_replace.htm Commented Oct 11, 2015 at 12:46

1 Answer 1

4

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']
Sign up to request clarification or add additional context in comments.

1 Comment

Wow nice compact form and still readable. @534, if it's not clear, the '{}' puts placeholders in the generic string to be filled in by the string.format() line.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.