Zac*_*aun 2 python recursion return-value python-3.x
我创建了一个尾递归函数来解决优化问题:
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']))
Run Code Online (Sandbox Code Playgroud)
该函数正常运行,但它无法返回任何内容.我并不是说第一个if语句永远不会被调用(事实上,当我取消注释打印行时,它将打印正确的结果),但是return语句无法返回字典.
这导致TypeError我试图打电话时optimized['best_price'],如'NoneType' object is not subscriptable.
我一直在研究这个错误一段时间,似乎无论是让自己工作还是在网上找到任何关于它的东西.在这一点上,我只想知道解决方案.有任何想法吗?谢谢!
甚至尾递归函数也需要return在Python中:
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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
320 次 |
| 最近记录: |