【问题标题】:Exercise 6 of Chapter 12 (Tuples) of Think Python by Allen DwneyAllen Downey 的 Think Python 第 12 章(元组)的练习 6
【发布时间】:2013-03-13 11:18:23
【问题描述】:

我正在向 Allen Downey 的 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]

【问题讨论】:

  • 每次运行 compute_childrenlongest_reducible 时,您都会创建相同的 words_dict。尝试这样做一次。
  • 并且一旦你完成了 Junuxx 的建议,你也可以先尝试测试最长的单词,一旦找到可还原的单词就停止。这意味着您可以完全忽略许多单词。
  • Python 的 profile 模块会告诉您代码在哪里花费时间,是一个值得学习如何使用的工具。

标签: python algorithm data-structures


【解决方案1】:
wdict = words_dict() #Builds a dictionary containing all valid English words...

大概,这需要一段时间。

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

【讨论】:

  • 哇,不知道自己完成一项很快就能完成的任务要花这么多时间。但我想它滚雪球,所有这些递归调用。谢谢!
  • @blindingflashofawesome:很好奇,你现在需要多长时间才能解决这个问题? :)
  • 不超过 4 秒。想想我浪费了一整天的时间在电脑上什么都不做!
猜你喜欢
  • 2023-03-18
  • 1970-01-01
  • 2015-02-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-10
  • 2018-06-06
相关资源
最近更新 更多