Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

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?

like image 304
quantumSoup Avatar asked Jul 23 '10 23:07

quantumSoup


People also ask

How do you increase maximum recursion depth?

The “maximum recursion depth exceeded in comparison” error is raised when you try to execute a function that exceeds Python's built in recursion limit. You can fix this error by rewriting your program to use an iterative approach or by increasing the recursion limit in Python.

What is the maximum depth of recursion function in Python?

Due to this, the recursion limit of python is usually set to a small value (approx, 10^4). This means that when you provide a large input to the recursive function, you will get an error. This is done to avoid a stack overflow. The Python interpreter limits the recursion limit so that infinite recursions are avoided.

How do I fix RecursionError maximum recursion depth exceeded while calling a Python object?

A Python RecursionError exception is raised when the execution of your program exceeds the recursion limit of the Python interpreter. Two ways to address this exception are increasing the Python recursion limit or refactoring your code using iteration instead of recursion.

How do you find the recursion depth in Python?

To get the current value of the recursion limit in Python, we will import sys module, and then we will use “sys. getrecursionlimit()” to get the current recursion limit.


2 Answers

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.

like image 172
Thomas Wouters Avatar answered Oct 03 '22 11:10

Thomas Wouters


Looks like you just need to set a higher recursion depth:

import sys sys.setrecursionlimit(1500) 
like image 45
David Young Avatar answered Oct 03 '22 11:10

David Young