首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >由Allen Dwney编写的思考Python第12章练习6(元组)

由Allen Dwney编写的思考Python第12章练习6(元组)
EN

Stack Overflow用户
提问于 2013-03-13 11:18:23
回答 1查看 560关注 0票数 5

我正在从艾伦·唐尼( Allen )的Think中学习python,我被困在了练习6 这里上。我为它写了一个解决方案,乍一看,它似乎比这里的答案有所改进。但在运行这两种方法时,我发现我的解决方案花了整整一天(大约22小时)来计算答案,而作者的解决方案只需几秒钟。有人能告诉我,当作者的解决方案在包含113,812个单词的字典上迭代并应用递归函数来计算结果时,它的速度是如此之快吗?

我的解决方案:

代码语言:javascript
复制
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]
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-03-13 11:31:16

代码语言:javascript
复制
wdict = words_dict() #Builds a dictionary containing all valid English words...

这大概需要一段时间。

然而,您重新生成这个相同的,不变的字典很多次对您试图减少的每一个单词。多浪费呀!如果您只制作了本词典一次,然后对您试图减少的每个单词重复使用该字典,就像您在known_red中所做的那样,计算时间应该会大大减少。

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15383799

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档