Allen Dwney的Think Python第12章(元组)练习6
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Allen Dwney的Think Python第12章(元组)练习6,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1970字,纯文字阅读大概需要3分钟。
内容图文
![Allen Dwney的Think Python第12章(元组)练习6](/upload/InfoBanner/zyjiaocheng/824/9f632881589c4a58814d5e12888425af.jpg)
我正在学习艾伦·唐尼的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]
解决方法:
wdict = words_dict() #Builds a dictionary containing all valid English words...
据推测,这需要一段时间.
但是,对于您尝试减少的每个单词,您会多次重新生成相同的,不变的字典.多么浪费!如果你创建一次这个字典,然后像你对known_red一样重复使用那个字典,那么你应该大大减少计算时间.
内容总结
以上是互联网集市为您收集整理的Allen Dwney的Think Python第12章(元组)练习6全部内容,希望文章能够帮你解决Allen Dwney的Think Python第12章(元组)练习6所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。