首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >尾递归函数返回值失败(Python 3)

尾递归函数返回值失败(Python 3)
EN

Stack Overflow用户
提问于 2011-09-08 05:17:14
回答 1查看 331关注 0票数 2

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

代码语言:javascript
运行
复制
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

我已经为这个错误工作了一段时间了,似乎既不能让它自己工作,也不能在网上找到任何关于它的东西。在这一点上,这只是我想知道解决方案的问题。有什么想法吗?谢谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-09-08 05:19:05

在Python语言中,即使是尾递归函数也需要return

代码语言:javascript
运行
复制
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)
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7340616

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档