Find all string combinations

I am looking for a way to get all combinations of string combinations from a sentence. For example, to enter input:

"I eat pizza"

I would like to get this output:

[["I", "am", "eating", "pizza"],
["I", "am eating", "pizza"],
["I", "am", "eating pizza"],
["I", "am eating pizza"],
["I am", "eating", "pizza"],
["I am", "eating pizza"],
["I am eating", "pizza"],
["I am eating pizza"]]

I cannot find a recursive way to do this! Do you have any ideas? This is not a duplicate: I am not looking for whole combinations, only ordered objects and always whole words. Cannot find my answer from the alleged duplicate.

+4
source share
2 answers

subdivide and repeat

Here you can do it with a recursive function - and how I approached the design:

  • Scan a row susing an indexi
  • If the index goes beyond the bounds, return the base result, [[s]]otherwise ...
  • a " " , A B , .
  • A: , .
  • B: ,
# split :: String -> [[String]]
def split (s, i = 0):
  if len(s) == i:
    return [[s]]
  elif s[i] == " ":
           # Part A                                     # Part B
    return [[s[0:i]] + acc for acc in split(s[i + 1:])] + split(s, i + 1)
  else:
    return split(s, i + 1)

print(split("i am eating pizza"))

# [ ['i', 'am', 'eating', 'pizza'], 
# , ['i', 'am', 'eating pizza']
# , ['i', 'am eating', 'pizza']
# , ['i', 'am eating pizza']
# , ['i am', 'eating', 'pizza']
# , ['i am', 'eating pizza']
# , ['i am eating', 'pizza']
# , ['i am eating pizza']
# ]
+1

2 ^ n.

, .

import itertools
input_string = "I am eating pizza"
split_string = input_string.split(' ')
lst = list(itertools.product([0, 1], repeat=len(split_string) - 1))

res = [] 
for entry in lst:
    round_output = []
    current = split_string[0]
    for i in range(len(entry)):
        if entry[i] == 1:
            current += ' ' + split_string[i+1]
        else:    
            round_output.append(current)
            current = split_string[i+1]
    round_output.append(current)
    res.append(round_output)
+1

Source: https://habr.com/ru/post/1691116/


All Articles