Python 是否优化尾递归?

编程入门 行业动态 更新时间:2024-10-10 07:32:31
本文介绍了Python 是否优化尾递归?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有以下代码失败并出现以下错误:

I have the following piece of code which fails with the following error:

RuntimeError: 超出最大递归深度

RuntimeError: maximum recursion depth exceeded

我试图重写它以允许尾递归优化 (TCO).我相信如果发生了 TCO,这段代码应该是成功的.

I attempted to rewrite this to allow for tail recursion optimization (TCO). I believe that this code should have been successful if a TCO had taken place.

def trisum(n, csum): if n == 0: return csum else: return trisum(n - 1, csum + n) print(trisum(1000, 0))

我应该断定 Python 不会产生任何类型的 TCO,还是只需要以不同的方式定义它?

Should I conclude that Python does not do any type of TCO, or do I just need to define it differently?

推荐答案

没有,以后也不会了 Guidovan Rossum 更喜欢能够有适当的回溯:

No, and it never will since Guido van Rossum prefers to be able to have proper tracebacks:

尾递归消除 (2009-04-22)

Tail Recursion Elimination (2009-04-22)

尾调用的最后一句话 (2009-04-27)

Final Words on Tail Calls (2009-04-27)

您可以通过如下转换手动消除递归:

You can manually eliminate the recursion with a transformation like this:

>>> def trisum(n, csum): ... while True: # Change recursion to a while loop ... if n == 0: ... return csum ... n, csum = n - 1, csum + n # Update parameters instead of tail recursion >>> trisum(1000,0) 500500

更多推荐

Python 是否优化尾递归?

本文发布于:2023-11-29 18:46:35,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1647289.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:递归   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!