Python 是否优化尾递归?

2023-09-27Python开发问题
1

本文介绍了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 是否优化尾递归?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

在xarray中按单个维度的多个坐标分组
groupby multiple coords along a single dimension in xarray(在xarray中按单个维度的多个坐标分组)...
2024-08-22 Python开发问题
15

Pandas中的GROUP BY AND SUM不丢失列
Group by and Sum in Pandas without losing columns(Pandas中的GROUP BY AND SUM不丢失列)...
2024-08-22 Python开发问题
17

GROUP BY+新列+基于条件的前一行抓取值
Group by + New Column + Grab value former row based on conditionals(GROUP BY+新列+基于条件的前一行抓取值)...
2024-08-22 Python开发问题
18

PANDA中的Groupby算法和插值算法
Groupby and interpolate in Pandas(PANDA中的Groupby算法和插值算法)...
2024-08-22 Python开发问题
11

PANAS-基于列对行进行分组,并将NaN替换为非空值
Pandas - Group Rows based on a column and replace NaN with non-null values(PANAS-基于列对行进行分组,并将NaN替换为非空值)...
2024-08-22 Python开发问题
10

按10分钟间隔对 pandas 数据帧进行分组
Grouping pandas DataFrame by 10 minute intervals(按10分钟间隔对 pandas 数据帧进行分组)...
2024-08-22 Python开发问题
11