2013-03-13 12 views
5

私はThink PythonのAllen Downeyのpythonを学んでいますが、私はエクササイズ6 hereで立ち往生しています。私はそれに解決策を書いた。最初の見解では、答えがhereであることを改善しているようだった。しかし、両方を実行すると、私の解決策は答えを計算するのに一日(約22時間)かかりましたが、著者の解答は数秒しかかかりませんでした。 誰も私に教えてください著者の解答は、113,812語の辞書を含む辞書を反復し、それぞれに再帰関数を適用して結果を計算するとどうなるのでしょうか?Allen Dwneyの第12章(タプル)の第12章(タプルル)

私のソリューション:

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] 
+4

'compute_children'または' longest_reducible'が実行されるたびに同じ 'words_dict'を行います。それを一度だけ試してみてください。 – Junuxx

+1

あなたがJunuxxの提案をしたら、最も長い単語を最初に試してみて、還元可能な単語を見つけたらすぐに中止することもできます。それはあなたが言葉の多くを無視することができるということです。 – Duncan

+1

Pythonの 'profile'モジュールは、あなたのコードがその時間を費やしている場所を教えてくれますし、使い方を学ぶ価値のあるツールです。 – martineau

答えて

5
wdict = words_dict() #Builds a dictionary containing all valid English words... 

はおそらく、これは時間がかかります。

しかし、あなたは減らすことを試みるすべての単語のために同じ、変わらない辞書を何度も再生成します。どのような無駄です!この辞書を一度作ってから、known_redのように減らそうとする単語ごとにその辞書を再利用すれば、計算時間を大幅に短縮することができます。

+1

うわー、それはすぐに完了したタスクを行うには時間がかかることを知らなかった。しかし、私は雪が降ったと思う、それらの再帰呼び出しのすべてで何が。 – Samarth

+0

@blindingflashofawesome:ちょうど不思議そう、あなたがこれを修正した今、どれくらい時間がかかりますか? :) – Junuxx

+0

4秒以下。そして、私はコンピュータ上で何もしない一日を無駄にしたと思っています! – Samarth

関連する問題