2011-09-07 6 views
2

テール

def optimize(current_price = 0.1, last_profit = 0.0): 
    current_profit = profit(current_price) 
    if (last_profit > current_profit) and (current_profit > 0.0): 
     return {'best_price': current_price - 0.1, 'best_profit': last_profit} 
     # print({'best_price': current_price - 0.1, 'best_profit': last_profit}) 
    else: 
     optimize(current_price + 0.1, current_profit) 

def best_price(): 
    optimized = optimize() # optimize() should return a dict, 
          # allowing optimized['best_price'] 
          # and optimized['best_profit'] to be called 
    print("Pricing the tickets at ${0} will produce the greatest profit, ${1}.".format(optimized['best_price'], optimized['best_profit'])) 

機能は、それが何を返すのに失敗したことを除いて正常に動作します。最初のifステートメントが呼び出されないと言っているわけではありません(実際には、印刷ラインのコメントを外すと正しい結果が出力されます)が、returnステートメントは辞書を返さないことを意味します。

optimized['best_price']'NoneType' object is not subscriptableとして呼び出しようとすると、TypeErrorになります。

私は今このエラーに取り組んでおり、自分自身を動作させたり、オンラインで何かを見つけることはできません。この時点で、解決策を知りたいのは私の問題です。何か案は?ありがとう!

+0

は、なぜあなたは 'if'の各選択肢に' return'を持っていませんか? –

答えて

5

でも末尾再帰関数はPythonでreturnを必要に:

def optimize(current_price = 0.1, last_profit = 0.0): 
    current_profit = profit(current_price) 
    if (last_profit > current_profit) and (current_profit > 0.0): 
     return {'best_price': current_price - 0.1, 'best_profit': last_profit} 
    else: # Add return below here 
     return optimize(current_price + 0.1, current_profit) 
+1

完璧!ありがとうございました!なぜこれが当てはまるのか説明できますか? (例えば、なぜreturn文が使われないうちにprint関数が動作するのでしょうか?) –

+0

"return文がないうちにprint関数が動作するのはなぜですか?"何? print - show outputのように、再帰関数から有用な値を返すこととは関係ありません。何を聞いていますか?おそらく、再帰に関する質問を検索すべきです。これらの質問のいずれも適切でない場合は、新しい質問を開く必要があります。 –

+0

あなたが私の質問を誤解した場合、私はお詫び申し上げます。私はそれを言い換えることができます:なぜ、2回目の「返却」を除外することは、私の辞書返還能力に影響しますが、それを印刷する能力には影響しません。除外が私の再帰機能を否定するかどうかは分かりますが、関数が明示的に再帰的に再帰していたので、正しい結果が出力されました。行方不明のものがあると確信していますが、再帰は幅広いテーマであり、今後の研究では単にガイダンスを探しています。 –

関連する問題