首页 > 解决方案 > 我们不能在 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"]))  
                                      

标签: pythondictionarydynamic-programmingmemoization

解决方案


推荐阅读