如何找到给定列表中的字符串组合,这些字符串加起来就是某个字符串(没有外部库)

2024-06-26 09:58:37 发布

您现在位置:Python中文网/ 问答频道 /正文

如果要形成的字符串是'abcde',而输入列表是['abc', 'd', 'ac', 'ab', 'e', 'abcd'] 形成字符串“abcde”的不同方法如下

(一)

(2)'abcd'+'e'

因此答案是2

我如何处理这个问题

我迄今为止的进展

character1 = input()
n = int(input())    # number of allowed inputs for list
list1 = [input() for i in range(n)]

1条回答
网友
1楼 · 发布于 2024-06-26 09:58:37

可以使用递归生成器函数:

d, s = ['abc', 'd', 'ac', 'ab', 'e', 'abcd'], 'abcde'
def get_combos(d, c = []):
  if ''.join(c) == s:
     yield c
  else:
     for i in d:
        if s.startswith(''.join(c)+i):
           yield from get_combos(d, c+[i])

print(list(get_combos(d)))

输出:

[['abc', 'd', 'e'], ['abcd', 'e']]

相关问题 更多 >