Interesting topic of recursion and stack overflow in class today and I wondered if there is any way of increasing the maximum recursion depth in Python? Wrote a quick function for finding the factorial of n using recursion:
def factorial(n):
if n == 1:
return n
else:
return n * factorial(n-1)
It can cope with factorial(994) but not factorial(995). The error given is:
RuntimeError: maximum recursion depth exceeded in comparison
Obviously a higher factorial can be found iteratively but, for the sake of argument and intrigue, can the maximum recursion depth be increased?
Conclusion. The recursion depth limit in Python is by default 1000 . You can change it using sys. setrecursionlimit() function.
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.
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.
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.
import sys
sys.setrecursionlimit(2000)
import sys
iMaxStackSize = 5000
sys.setrecursionlimit(iMaxStackSize)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With