尾部递归函数无法返回值(Python3)

2024-03-28 18:21:16 发布

您现在位置: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}
        # 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。在

我已经处理这个错误有一段时间了,我似乎不能让它发挥作用,也不能在网上找到任何关于它的信息。在这一点上,我只是想知道解决办法。有什么想法吗?谢谢!在


Tags: andthereturnifdef语句currentprice
1条回答
网友
1楼 · 发布于 2024-03-28 18:21:16

在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)

相关问题 更多 >