我创建了一个尾递归函数来解决一个优化问题:
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
语句从未被调用过(实际上,当我取消对打印行的注释时,它将打印出正确的结果),而是说返回语句无法返回字典。
当我试图以'NoneType' object is not subscriptable
的身份调用optimized['best_price']
时,这会导致一个TypeError
。
我已经为这个错误工作了一段时间了,似乎既不能让它自己工作,也不能在网上找到任何关于它的东西。在这一点上,这只是我想知道解决方案的问题。有什么想法吗?谢谢!
发布于 2011-09-08 05:19:05
在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)
https://stackoverflow.com/questions/7340616
复制相似问题