Python Recursion

1. Basic Recursive Function

def print_numbers(n):
    if n == 0:
        return
    print(n)
    print_numbers(n - 1)

print_numbers(5)

A recursive function calls itself to solve a smaller instance of the same problem.


2. Base Case and Recursive Case

def factorial(n):
    if n == 0:          # Base case
        return 1
    return n * factorial(n - 1)  # Recursive case

print(factorial(5))  # Output: 120

Every recursive function must define a base case to prevent infinite calls.


3. Recursive Sum of Numbers

Demonstrates problem decomposition through recursion.


4. Recursive Fibonacci Series

Classic example of overlapping subproblems in recursion.


5. Recursion vs Iteration Comparison

Iteration often provides better performance and memory efficiency than deep recursion.


6. Recursive Traversal of List

Recursion is useful for navigating hierarchical or nested data.


7. Recursive String Reversal

Illustrates recursive manipulation of sequences.


8. Recursion Limit Error

Python enforces a recursion limit to prevent stack overflow.


9. Checking Recursion Depth

System recursion limits can be queried and adjusted cautiously.


10. Optimizing Recursion with Memoization

Memoization dramatically improves performance by caching results.


Last updated