Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How could you increase the maximum recursion depth in Python? [duplicate]

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?

like image 963
Rob Murray Avatar asked Nov 17 '15 13:11

Rob Murray


People also ask

How do you increase maximum recursion depth in Python?

Conclusion. The recursion depth limit in Python is by default 1000 . You can change it using sys. setrecursionlimit() function.

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 you solve 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.


2 Answers

import sys

sys.setrecursionlimit(2000)
like image 59
Ayush Avatar answered Jan 04 '23 04:01

Ayush


import sys

iMaxStackSize = 5000
sys.setrecursionlimit(iMaxStackSize)
like image 42
Mangu Singh Rajpurohit Avatar answered Jan 04 '23 04:01

Mangu Singh Rajpurohit