Python Recursion Cheat Sheet
Quick Reference
1. What is Recursion?
- A function calling itself to solve a smaller subproblem.
- Key Components: Base Case (stopping condition) and Recursive Case (smaller call).
2. General Structure:
def recursive_function(params):
if base_case_condition:
return base_case_value
else:
return recursive_function(smaller_problem)
3. Common Examples:
Factorial:
def factorial(n):
if n == 0:
return 1
return n * factorial(n - 1)
Fibonacci:
def fib(n):
if n <= 1:
return n
return fib(n-1) + fib(n-2)
4. Tips:
- Always define a base case to avoid infinite recursion.
- Watch recursion depth: Python's default limit ~1000 calls.
- Tail recursion is not optimized in Python.
5. When to Use:
- Tree traversal (DFS, preorder/inorder/postorder)
- Divide & conquer (merge sort, quick sort)
- Backtracking (maze solving, permutations)
6. Visualizing the Call Stack:
factorial(3):
factorial(3) -> factorial(2) -> factorial(1) -> factorial(0)
Returns back in reverse order.
Python Recursion Cheat Sheet
7. Debugging:
- Add print statements to track calls.
- Use sys.setrecursionlimit(new_limit) to increase depth (use with caution).