Allen Dwney的Think Python第12章(元组)练习6

Allen Dwney的Think Python第12章(元组)练习6,python,algorithm,data-structures,Python,Algorithm,Data Structures,我正在向艾伦·唐尼的《思考python》学习python,我被困在练习6中。我为它写了一个解决方案,乍一看,它似乎比给出的答案有所改进。但在运行这两个程序后,我发现我的解决方案花了一整天(约22小时)来计算答案,而作者的解决方案只花了几秒钟。 有谁能告诉我,当作者的解决方案迭代一个包含113812个单词的字典并对每个单词应用一个递归函数来计算结果时,它的速度有多快 我的解决方案: known_red = {'sprite': 6, 'a': 1, 'i': 1, '': 0} #Global

我正在向艾伦·唐尼的《思考python》学习python,我被困在练习6中。我为它写了一个解决方案,乍一看,它似乎比给出的答案有所改进。但在运行这两个程序后,我发现我的解决方案花了一整天(约22小时)来计算答案,而作者的解决方案只花了几秒钟。 有谁能告诉我,当作者的解决方案迭代一个包含113812个单词的字典并对每个单词应用一个递归函数来计算结果时,它的速度有多快

我的解决方案:

known_red = {'sprite': 6, 'a': 1, 'i': 1, '': 0}  #Global dict of known reducible words, with their length as values

def compute_children(word):
   """Returns a list of all valid words that can be constructed from the word by removing one letter from the word"""
    from dict_exercises import words_dict
    wdict = words_dict() #Builds a dictionary containing all valid English words as keys
    wdict['i'] = 'i'
    wdict['a'] = 'a'
    wdict[''] = ''
    res = []

    for i in range(len(word)):
        child = word[:i] + word[i+1:]
        if nword in wdict:
            res.append(nword)

    return res

def is_reducible(word):
    """Returns true if a word is reducible to ''. Recursively, a word is reducible if any of its children are reducible"""
    if word in known_red:
        return True
    children = compute_children(word)

    for child in children:
        if is_reducible(child):
            known_red[word] = len(word)
            return True
    return False

def longest_reducible():
    """Finds the longest reducible word in the dictionary"""
    from dict_exercises import words_dict
    wdict = words_dict()
    reducibles = []

    for word in wdict:
        if 'i' in word or 'a' in word: #Word can only be reducible if it is reducible to either 'I' or 'a', since they are the only one-letter words possible
            if word not in known_red and is_reducible(word):
                known_red[word] = len(word)

    for word, length in known_red.items():
        reducibles.append((length, word))

    reducibles.sort(reverse=True)

    return reducibles[0][1]
这大概需要一段时间


然而,对于您试图精简的每个单词,您都会多次重新生成相同的、不变的词典。真是浪费!如果您制作一次此词典,然后对您尝试减少的每个单词重复使用该词典,就像您为
已知的
所做的那样,计算时间应该会大大减少。

每次运行
计算子项
最长的可减少的时,您都会制作相同的
单词。试着只做一次。一旦你完成了Junuxx的建议,你也可以试着先测试单词最长,一旦你找到一个可以还原的单词,就停止。这意味着您可以完全忽略许多单词。Python的
profile
模块将告诉您代码在哪里花费时间,并且是一个值得学习如何使用的工具。哇,我不知道自己花了那么多时间来完成一项很快就完成的任务。但是我想它滚雪球了,因为所有这些递归调用。谢谢@令人眼花缭乱的闪现恐惧:只是好奇,你修复这个需要多长时间不超过4秒。想想我浪费了一整天在电脑上什么都不做!
wdict = words_dict() #Builds a dictionary containing all valid English words...