How to fix recursionerror: maximum recursion depth exceeded

In Python, we have a limitation for recursion depth (by default 1000). We get this error when our recursion function exceeded this value. We need this limit to avoid infinite recursion. If you faced with this error you can use the next decision:

Change recursion limit using 'getrecursionlimit' function from the 'sys' module.

For example, we have a recursive function for counting occurrences of the character in the string. I deliberately lowered this limit to 10 before the first call to this function. This limit is not sufficient to successfully complete the function so in try/except block we get this error. After the first call, I increase this limit to 100 so the second call was successful.

import sys

def check(my_string, char):
    if not my_string:
        return 0
    elif my_string[0] == char:
        return 1 + check(my_string[1:], char)
    else:
        return check(my_string[1:], char)

print(f"Deafault recursion limit: {sys.getrecursionlimit()}")
sys.setrecursionlimit(10)
print(f"Current recursion limit: {sys.getrecursionlimit()}")

string = "fhfbbffffbdfbdfffbdfbfffbdff"
ch = "f"

try:
    print(f"Number of occurrences: {check(string, ch)}")
except RecursionError as e:
    print(f"You get this error: {e}")

sys.setrecursionlimit(100)
print(f"Current recursion limit: {sys.getrecursionlimit()}")
print(f"Number of occurrences: {check(string, ch)}")

Output:

Deafault recursion limit: 1000
Current recursion limit: 10
You get this error: maximum recursion depth exceeded in comparison
Current recursion limit: 100
Number of occurrences: 16
#python
0
Roman Ivashchenko profile picture
Dec 11, 2020
by Roman Ivashchenko
Did it help you?
Yes !
No

Best related