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

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

当我尝试调用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/

相关文章:

python - 在 Python : "" or None? 中初始化一个字符串变量

python - 为什么允许列表自行追加?

python - 在相似的多个按钮之间单击时更改按钮颜色

python /基维 : not working properly vertical scrollbar in dynamic row

python - 应用函数来操作 Python Pandas DataFrame 组

python - 使用pyinstaller打包python文件后,创建的可运行文件转储

python - 有没有办法将数字单词转换为整数?

python - 获取 self 的命名属性

sql-server - 递归地对相似的项目进行分组

javascript - 使用递归函数比较 JavaScript 中的对象