PromptHub
Python Intermediate 11 views

Python RecursionError

The function calls itself too many times, exceeding the maximum recursion depth.

Explanation

RecursionError occurs when a function calls itself recursively more times than Python's default recursion limit (typically 1000). Python has a limited call stack to prevent infinite recursion from crashing the program. This happens when the base case is missing, the base case is never reached, or the recursion depth is genuinely needed but exceeds the limit. Infinite recursion will eventually raise RecursionError after hitting the depth limit.

Common Causes

  • Missing base case in recursion
  • Base case never reached
  • Recursive call doesn't progress
  • Deep data structure traversal
  • Circular references

Solution

Add a proper base case to stop recursion. Verify the recursive call actually moves toward the base case. Consider converting recursive algorithms to iterative ones using loops and explicit stacks. Increase the recursion limit with sys.setrecursionlimit() only as a temporary measure. Use memoization with functools.lru_cache to reduce redundant recursive calls. For tree traversal, consider iterative approaches using collections.deque.

Code Example

# Missing base case - infinite recursion
def factorial(n):
    return n * factorial(n - 1)  # no base case!

# Fix: add base case
def factorial(n):
    if n <= 1:  # base case
        return 1
    return n * factorial(n - 1)

# Recursive call doesn't progress toward base case
def count_down(n):
    print(n)
    return count_down(n)  # always calls with same n!

# Fix
def count_down(n):
    if n <= 0:
        print("Done!")
        return
    print(n)
    return count_down(n - 1)  # n decreases each time

# Convert to iterative
def factorial_iterative(n):
    result = 1
    for i in range(2, n + 1):
        result *= i
    return result

# Increase limit (temporary fix)
import sys
sys.setrecursionlimit(5000)

Error Information

Language

python

Difficulty

Intermediate

Views

11

Related Errors