I have a list:
["toaster", "oven", "door"]
I need to get ALL the possible sequential words that can be created. The output should look like this:
["toaster", "toaster oven", "toaster oven door", "oven", "oven door", "door"]
What is the most efficient way to get this list? I've looked at itertools.combinations() and a few other suggestions found on Stack Overflow, but nothing that would produce this exact result.
For example, the above list is not a powerset, because only words adjacent to each other in the input list should be used. A powerset would combine toaster and door into toaster door, but those two words are not adjacent.
You can do it like this:
words = ["toaster", "oven", "door"]
length = len(words)
out = []
for start in range(length):
for end in range (start+1, length+1):
out.append(' '.join(words[start:end]))
print(out)
# ['toaster', 'toaster oven', 'toaster oven door', 'oven', 'oven door', 'door']
You just need to determine the first and last word to use.
You could also use a list comprehension:
[' '.join(words[start:end]) for start in range(length) for end in range(start+1, length+1)]
#['toaster', 'toaster oven', 'toaster oven door', 'oven', 'oven door', 'door']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With