python - 我们不能在 python 方法的争论中初始化字典吗?
问题描述
我有这两个代码:用于查找我们可以使用 wordBank 构造目标字符串的所有方法。我目前正在学习记忆。第二个代码给出了错误的答案,就像最后一个代码部分中给出的不同调用的备忘录一样。
def all_construct(target, word_bank):
memo = {}
def helper(target, word_bank):
if target == "":
return [[]]
if target in memo:
return memo[target]
result = []
for word in word_bank:
if len(target) >= len(word) and target[: len(word)] == word:
suffix = target[len(word) :]
suffix_ways = helper(suffix, word_bank)
target_ways = [[word] + way for way in suffix_ways]
if target_ways:
result.extend(target_ways)
memo[target] = result
return result
return helper(target, word_bank)
和
def allConstruct(target, wordBank, memo = {}):
if target in memo : return memo[target]
if target == "": return [[]]
totalWays = []
for x in wordBank:
if target[:len(x)] == x:
remainderWays = allConstruct(target[len(x):], wordBank, memo)
for y in remainderWays:
y.insert(0, x)
totalWays += remainderWays
memo[target] = totalWays
return totalWays
来电:
print(all_construct("purple", ["purp", "p", "ur", "le", "purpl"]))
print(all_construct("abcdef", ["ab", "abc", "cd", "def", "abcd","ef"]))
print(all_construct("enterapotentpot", ["a", "p", "ent", "enter", "ot", "o", "t"]))
print(all_construct("eeeeeeeeeeef", ["e", "ee", "eee", "eeee", "eeeee", "eeeeee"]))
解决方案
推荐阅读
- angular - TypeError:没有'new'就不能调用类构造函数DefaultValueAccessor
- iframe - 如何通过悬停 iframe 动态获取 iframe 内的元素
- node.js - 堆限制分配失败-JavaScript 堆内存不足-ng 服务后 Angular 4 编译错误
- haskell - Alex monad wrapper 之间的区别;并跳过
- python - 进行 and 语句时,出现语法错误
- android - 约束布局的水平方向不起作用
- devexpress - 使用自定义编辑按钮在编辑模式下打开 DevExpress MVC Grid
- elasticsearch - 复制到 ElasticSearch 中的动态或自定义字段
- python - 从运行 Tkinter GUI 中删除单选按钮
- php - Apache 上未启用 PHP (Mac OS 10.14.1 Mojave)