尾递归函数无法返回值(Python 3)

时间:2011-09-07 21:17:14

标签: python recursion python-3.x return-value

我创建了一个尾递归函数来解决优化问题:

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语句无法返回字典。

当我尝试将TypeError作为optimized['best_price']时,这会产生'NoneType' object is not subscriptable

我一直在研究这个错误已经有一段时间了,似乎无论是让自己工作还是在网上找不到任何相关信息。在这一点上,我只想知道解决方案。有任何想法吗?谢谢!

1 个答案:

答案 0 :(得分: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)