按给定字符串的顺序组合

In order combinations given a string

我正在尝试按顺序创建单词音节的所有可能组合。

例如,我有单词 overflowing 并且我有它的音节列表 ['o', 'ver', 'flow', 'ing']。我希望输出显示组合音节的所有可能组合以组成单词:[('o', 'ver', 'flow', 'ing'), ('o', 'verflow', 'ing'), ('o', 'verflowing'), ('overflowing'), ('over', 'flow', 'ing'), ...].

这是我的尝试:

syllable_list = ['o', 'ver', 'flow', 'ing']
list_length = len(syllable_list)
for x in range(0, list_length):
    for y in range(0, list_length):
        if syllable_list[y:x+1]:
            before = ""
            middle = ""
            after = ""
            if syllable_list[0:y]:
                before = ["".join(syllable_list[0:y])]
            if syllable_list[x+1:]:
                after = ["".join(syllable_list[x+1:])]
            middle = ["".join(syllable_list[y:x+1])]
            print(before, middle, after)

输出为:

 ['o'] ['verflowing']
 ['over'] ['flowing']
['o'] ['ver'] ['flowing']
 ['overflow'] ['ing']
['o'] ['verflow'] ['ing']
['over'] ['flow'] ['ing']
 ['overflowing']
['o'] ['verflowing']
['over'] ['flowing']
['overflow'] ['ing']

所有的组合都在那里,有一些重复,我遗漏了 ['o', 'ver', 'flow', 'ing'] 的情况。我究竟做错了什么?是否有已经处理此问题的库,因此我不必重新创建轮子?

您可以使用递归生成器将任意两个连续元素组合起来进行下一级递归:

>>> def generate(parts, start=0):
...     yield parts
...     for i in range(start, len(parts)-1):
...         yield from generate([*parts[:i], parts[i]+parts[i+1], *parts[i+2:]], start=i)
... 
>>> from pprint import pprint
>>> pprint(list(generate(['o', 'ver', 'flow', 'ing'])))
[['o', 'ver', 'flow', 'ing'],
 ['over', 'flow', 'ing'],
 ['overflow', 'ing'],
 ['overflowing'],
 ['over', 'flowing'],
 ['o', 'verflow', 'ing'],
 ['o', 'verflowing'],
 ['o', 'ver', 'flowing']]

由于您只定义了 3 个变量(After、middle 和 before),所以您无法获得超过 3 个字符串的输出。

您的代码将始终连接至少 2 个字符串。

你需要找到另一种方法来做到这一点。