python - 如何在给定列表中找到加起来为某个字符串的字符串组合(没有外部库)
问题描述
如果要形成的字符串是'abcde'并且输入列表是['abc', 'd', 'ac', 'ab', 'e', 'abcd']
形成字符串'abcde'的不同方式将是
(1)'abc'+'d'+'e'
(2)'abcd'+'e'
因此答案是 2。
我该如何解决这个问题?
到目前为止我的进步;_;
character1 = input()
n = int(input()) # number of allowed inputs for list
list1 = [input() for i in range(n)]
解决方案
您可以使用递归生成器函数:
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']]
推荐阅读
- twilio-programmable-chat - Twilio 聊天 - getUnconsumedMessagesCount 返回 null
- go - 如何在 Golang 中将“uint”类型转换为“string”类型?
- javascript - 如何将数组中的对象分配给箭头函数?
- amazon-s3 - AWS DMS CDC 到 S3 目标
- unit-testing - 我们如何测试类没有默认构造函数?类不可实例化?
- r - R 中的 AWS API - 添加了授权标头但获得 InvalidSignatureException
- mysql - JHipster 未知数据库连接错误
- scala - 尝试在纱线集群中使用外部 jar 时获取类未找到异常
- python - tensorflow一直无效训练,才几百步,loss很快降到0,准确率达到100%,困扰了我好几个月
- java - 对 RecyclerView 的更改导致此错误:E/RecyclerView: No adapter attach; 跳过布局