《Think Python》第12章(元组)第6题
我正在学习Python,书名是《Think Python》,作者是艾伦·道尼。我在第六个练习上遇到了困难,具体内容可以在这里找到。我写了一个解决方案,乍一看似乎比书中给出的答案要好一些,链接在这里。但是,当我运行这两个方案时,我发现我的解决方案计算结果花了整整一天(大约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 个回答
5
wdict = words_dict() #Builds a dictionary containing all valid English words...
可以推测,这个过程需要一些时间。
不过,你为每个想要简化的单词都重复生成这个相同的、不变的字典,这真是浪费时间!如果你只生成一次这个字典,然后像处理 known_red
一样,重复使用这个字典来处理每个单词,那么计算的时间应该会大大减少。