Russian nesting dolls of code
Day 5 of 149
π Full deep-dive with code examples
The Nesting Dolls
Russian nesting dolls (Matryoshka):
- Open the big doll
- There's a smaller doll inside
- Open that one
- Another smaller doll inside
- Keep going until the smallest one
Recursion is a function calling itself!
In Code
A function that calls itself to solve smaller pieces:
def countdown(n):
if n == 0:
print("Liftoff! π")
else:
print(n)
countdown(n - 1) # Calls itself!
countdown(3)
# Output: 3, 2, 1, Liftoff! π
Each call handles a smaller problem (n-1) until we hit the base case (n=0).
The Two Rules
Every recursive function needs:
- Base Case β When to stop (the smallest doll)
- Recursive Case β Call itself with a smaller problem
Without a base case, it can behave like an infinite loop = π₯
Classic Example: Factorial
5! = 5 Γ 4 Γ 3 Γ 2 Γ 1
But also: 5! = 5 Γ 4!
def factorial(n):
if n == 1: # Base case
return 1
else:
return n * factorial(n-1) # Recursive case
In One Sentence
Recursion is solving a problem by breaking it into smaller versions of the same problem.
π Enjoying these? Follow for daily ELI5 explanations!
Making complex tech concepts simple, one day at a time.
Top comments (0)