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

时间:2013-03-13 11:18:24

标签: python algorithm data-structures

我正在学习艾伦·唐尼的Think Python中的python,而且我被困在练习6 here。我给它写了一个解决方案,起初看起来似乎是对here给出的答案的改进。但是在运行两者时,我发现我的解决方案需要一整天(约22小时)来计算答案,而作者的解决方案只花了几秒钟。 任何人都可以告诉我如何作者的解决方案是如此之快,当它迭代一个包含113,812个单词的字典并对每个单词应用递归函数来计算结果时?

我的解决方案:

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]

1 个答案:

答案 0 :(得分:5)

wdict = words_dict() #Builds a dictionary containing all valid English words...

据推测,这需要一段时间。

但是,对于您尝试减少的每个单词,会多次重新生成相同的,不变的字典。多么浪费!如果你创建一次这个字典,然后像你对known_red那样尝试减少每个单词重复使用该字典,那么计算时间应该大大减少。