Skip to content

[Solved][Python] RecursionError: maximum recursion depth exceeded

Problem

In Python, in order to prevent stack overflow (using too much memory to cause), the recursion we use has a limit on the number of layers. Once we use the recursion depth exceeding the preset limit, the following error will be triggered:

RecursionError: maximum recursion depth exceeded

We have two solutions to solve this problem:

  1. Rewrite recursive algorithm (optimization)
  2. Set the recursion depth limit (although not recommended, this method is faster, you can choose after measuring your own equipment)

Set the recursion depth limit

We can use the following code to confirm the current recursion depth:

import sys
print(sys.getrecursionlimit())


Output:

1000

Basically, the default depth of Python is 1000, and we can adjust this depth through programs. Assuming that we need to set the depth to 2000, then we write at the beginning of the program:

sys.setrecursionlimit(2000)



As a result, the program that would have reported an error should be able to execute normally.


References


Read More

Tags:

Leave a Reply