Intermediate·7 min·intermediate · algorithms
Recursion
Recursion
A function that calls itself. Every recursion has two parts:
- Base case — when do we stop?
- Recursive case — call ourselves with a smaller subproblem.
When it shines
- Tree / graph traversals
- Anything naturally defined "in terms of itself" (factorial, fib, parsers)
- Quick & dirty divide-and-conquer
Pitfalls
- Forgetting the base case →
RecursionError - Python's default recursion limit is ~1000; deep recursion needs
sys.setrecursionlimitor an iterative rewrite.
Try it
- Write a recursive
flatten([1, [2, [3, 4]]])→[1, 2, 3, 4]. - Use recursion to reverse a list.