I am learning python from Think Python from Allen Downey and I am stuck in Exercise 6 here . I wrote a solution for her, and at first it looked like an improvement over the answer here . But when I started both of them, I found that my solution took a whole day (~ 22 hours) to calculate the answer, while the author's solution took only a couple of seconds. Can someone tell me how the author’s solution is so fast when iterating over a dictionary containing 113,812 words and applying a recursive function for each to calculate the result?
My decision:
known_red = {'sprite': 6, 'a': 1, 'i': 1, '': 0}
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()
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:
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]
source
share