我正在从艾伦·唐尼( Allen )的Think中学习python,我被困在了练习6 这里上。我为它写了一个解决方案,乍一看,它似乎比这里的答案有所改进。但在运行这两种方法时,我发现我的解决方案花了整整一天(大约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]发布于 2013-03-13 11:31:16
wdict = words_dict() #Builds a dictionary containing all valid English words...这大概需要一段时间。
然而,您重新生成这个相同的,不变的字典很多次对您试图减少的每一个单词。多浪费呀!如果您只制作了本词典一次,然后对您试图减少的每个单词重复使用该字典,就像您在known_red中所做的那样,计算时间应该会大大减少。
https://stackoverflow.com/questions/15383799
复制相似问题