python - Python在一个函数中组合多个List
问题描述
嗨,我坚持将所有列表合并为最终列表。代码是在给定主字符串的情况下找到子集字符串的可能组合。
该代码能够找到所有可能的组合,但是我不知道如何组合结果
#for 'abcd', given ['a','b','c','bc','d']
#the out put shall be
#[['a','b','c','d'],['a','bc','d']]
def canConstruct(target_string,words,memo=None,):
if memo == None: memo = dict()
if target_string in memo:
return memo[target_string]
if target_string == "": return []
for word in words:
if target_string.startswith(word):
remainder_string = target_string[len(word):]
bank = canConstruct(remainder_string,words,memo)
bank = [word] + bank
print(bank)
return bank
print(canConstruct('abcd',['a','bc','b','c','d']))
解决方案
将结果收集到一个列表中:
# ...
if target_string == "":
return [[]] # result is list of lists!
result = []
for word in words:
if target_string.startswith(word):
remainder_string = target_string[len(word):]
for cc in canConstruct(remainder_string, words, memo):
result.append([word] + cc)
memo[target_string] = result
return result
推荐阅读
- c# - Windows 窗体的权限是否比控制台应用程序少?
- python - 如何从 OrderedDicts 列表中创建 Pandas DataFrame?
- postgresql - Flask-Alembic 错误 sqlalchemy.exc.ProgrammingError: (psycopg2.ProgrammingError) 类型不存在
- algorithm - 使用数组进行归并排序的空间复杂度
- php - 在非对象 PHP PDO 上调用成员函数 prepare()
- python - 谐音替换密码 Python
- r - 如何在 R 中安装“Hmisc”
- regex - 正则表达式包含两个单词,但排除一个空格,后面跟任何不是字符串末尾的空格
- javascript - 当分析调用来自 IFRAME 时,Google Analytics 如何绕过同源策略?
- firebase - 将带有 JSON 数据的 HTTP 请求发送到 Firebase 函数