Python: How to produce only in sequence combinations from a list of string parts, with use being optional

StackOverflow https://stackoverflow.com/questions/22560201

  •  18-06-2023
  •  | 
  •  

Question

I would like to know how I can produce only in sequence combinations from a list of string parts, with use being optional. I need to do this in Python.

For example:

Charol(l)ais (cattle) is my complete string, with the parts in brackets being optional.

From this I would like to produce the following output as an iterable:

Charolais
Charollais
Charolais cattle
Charollais cattle

Was looking at Python's itertools module, since it has combinations; but couldn't figure out how to use this for my scenario.

Was it helpful?

Solution

You will need to convert the string into a more sensible format. For example, a tuple of all of the options for each part:

words = [("Charol",), ("l", ""), ("ais ",), ("cattle", "")]

And you can easily put them back together:

for p in itertools.product(*words):
    print("".join(p))

To create the list, parse the string, e.g.:

base = "Charol(l)ais (cattle)"
words = []
start = 0
for i, c in enumerate(base):
    if c == "(":
        words.append((base[start:i],))
        start = i + 1
    elif c == ")":
        words.append((base[start:i], ""))
        start = i + 1
if start < len(base):
    words.append((base[start:],))

OTHER TIPS

You could use the permutations from itertools and denote your optional strings with a special character. Then, you can replace those either with the correct character or an empty string. Or carry on from this idea depending on the exact semantics of your task at hand.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top