What is the maximum recursion depth in Python, and how to increase it?

I have this tail recursive function here:

def fib(n, sum):
    if n < 1:
        return sum
    else:
        return fib(n-1, sum+n)

c = 998
print(fib(c, 0))

It works up to n=997, then it just breaks and spits a "maximum recursion depth exceeded in comparison" RuntimeError . Is this just a stack overflow? Is there a way to get around it?


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 change the recursion limit with sys.setrecursionlimit , but doing so is dangerous -- the standard limit is a little conservative, but Python stackframes can be quite big.

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.


看起来你只需要设置一个更高的递归深度

sys.setrecursionlimit(1500)

It's to avoid a stack overflow. The Python interpreter limits the depths of recursion to help you avoid infinite recursions, resulting in stack overflows. Try increasing the recursion limit (sys.setrecursionlimit) or re-writing your code without recursion.

from python website:

sys.getrecursionlimit()

Return the current value of the recursion limit, the maximum depth of the Python interpreter stack. This limit prevents infinite recursion from causing an overflow of the C stack and crashing Python. It can be set by setrecursionlimit().

链接地址: http://www.djcxy.com/p/80676.html

上一篇: 在Python中用于和如何/何时使用它,以及它是如何工作的

下一篇: Python中的最大递归深度是多少,以及如何增加它?