问题描述
我在这里有这个尾递归函数:
I have this tail recursive function here:
def recursive_function(n, sum):
if n < 1:
return sum
else:
return recursive_function(n-1, sum+n)
c = 998
print(recursive_function(c, 0))
它最多可以工作到 n=997
,然后它就会中断并吐出一个RecursionError:比较时超出了最大递归深度
.这只是堆栈溢出吗?有没有办法绕过它?
It works up to n=997
, then it just breaks and spits out a RecursionError: maximum recursion depth exceeded in comparison
. Is this just a stack overflow? Is there a way to get around it?
推荐答案
它是一种防止堆栈溢出的方法,是的.Python(或者更确切地说,CPython 实现)不会优化尾递归,并且无节制的递归会导致堆栈溢出.您可以使用 sys.getrecursionlimit
检查递归限制一个>:
It is a guard against a stack overflow, yes. Python (or rather, the CPython implementation) doesn't optimize tail recursion, and unbridled recursion causes stack overflows. You can check the recursion limit with sys.getrecursionlimit
:
import sys
print(sys.getrecursionlimit())
并使用 sys.setrecursionlimit
更改递归限制:
and change the recursion limit with sys.setrecursionlimit
:
sys.setrecursionlimit(1500)
但这样做很危险——标准限制有点保守,但 Python 堆栈帧可能相当大.
but doing so is dangerous -- the standard limit is a little conservative, but Python stackframes can be quite big.
Python 不是函数式语言,尾递归也不是特别有效的技术.如果可能,迭代地重写算法通常是一个更好的主意.
Python isn't a functional language and tail recursion is not a particularly efficient technique. Rewriting the algorithm iteratively, if possible, is generally a better idea.
这篇关于Python中的最大递归深度是多少,如何增加?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!