snippetpythonCritical
What is the maximum recursion depth, and how to increase it?
Viewed 0 times
howthemaximumandincreasewhatrecursiondepth
Problem
I have this tail recursive function here:
It works up to
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))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?Solution
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
and change the recursion limit with
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.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.
Code Snippets
import sys
print(sys.getrecursionlimit())sys.setrecursionlimit(1500)Context
Stack Overflow Q#3323001, score: 857
Revisions (0)
No revisions yet.