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

前端 未结 17 2970
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-21 04:14

I have this tail recursive function here:

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


        
17条回答
  •  忘掉有多难
    2020-11-21 05:02

    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())
    

    and change the recursion limit with sys.setrecursionlimit:

    sys.setrecursionlimit(1500)
    

    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.

提交回复
热议问题