0% found this document useful (0 votes)
1 views2 pages

Python Recursion Cheatsheet

This cheat sheet provides a quick reference for Python recursion, explaining its definition, structure, and common examples like factorial and Fibonacci functions. It emphasizes the importance of base cases, recursion depth, and scenarios where recursion is applicable, such as tree traversal and backtracking. Additionally, it includes tips for debugging and visualizing the call stack.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views2 pages

Python Recursion Cheatsheet

This cheat sheet provides a quick reference for Python recursion, explaining its definition, structure, and common examples like factorial and Fibonacci functions. It emphasizes the importance of base cases, recursion depth, and scenarios where recursion is applicable, such as tree traversal and backtracking. Additionally, it includes tips for debugging and visualizing the call stack.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

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).

You might also like