我创建了一个尾递归函数来解决优化问题:
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']
时,这会导致TypeError
,因为'NoneType'对象不可订阅
。
我已经解决这个错误有一段时间了,似乎无法自己解决这个问题,也无法在网上找到任何相关的信息。目前,我只是想知道解决方案。有任何想法吗?谢谢!
最佳答案
在 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)
关于python - 尾递归函数无法返回值(Python 3),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7340616/