In this post, we will see about Maximum recursion depth reached in Python.This can be solved by increase the recursion depth in python.
If you are getting Runtime error Maximum recursion depth reached. then you can increase default recursion depth which is by default 1000.
You need to import sys module in your script and put following code.
1 2 3 |
sys.setrecursionlimit(1500) |
It will increase default recursion depth to 1500.
But I won’t recommend using this tactic instead you should rewrite your algorithm to an iterative one if possible. Python does not optimize tail recursion and uncontrolled recusion causes stack overflows.
For example:
Instead of fibonacci recusive algoroithm
1 2 3 4 5 6 7 |
def recursive_fibonacci(n): if n <= 1: return n else: return(recur_fibo(n-1) + recur_fibo(n-2)) |
You can use iterative algorithm.
1 2 3 4 5 6 7 |
def iterative_fibonacci(n): fibs = [0, 1, 1] for f in range(2, n): fibs.append(fibs[-1] + fibs[-2]) return fibs[n] |
That’s all about Maximum recursion depth reached in Python.