我正在寻找一种从句子中获取所有字符串拆分组合的方法。 例如,对于输入的发送:
"我正在吃披萨"
我想得到这个输出:
[["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"]]
我无法找到这样做的递归方式!你有什么主意吗 ? 这不是重复:我不是在寻找整个组合,只是订购商品,而是整个单词。无法从所谓的副本中找到答案。
答案 0 :(得分:1)
感谢Alfe对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 :(得分:1)
细分并重复
这是一种使用递归函数的方法 - 以及我如何处理设计:
s
i
[[s]]
,否则...... " "
,请将问题细分为 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']
# ]