Skip to main content

Command Palette

Search for a command to run...

πŸͺ† Recursion Explained Like You're 5

Published
β€’2 min read
S

Building AI systems and writing about how they actually work. Master of AI @ University of Technology Sydney. Previously B.Tech CS with focus on IoT. I believe the best way to learn is to explain. That's why I'm documenting tech concepts with simple analogies (@sreekarreddy.com). AWS Certified β€’ Azure AI Certified β€’ Neo4j Professional β€’ Google Data Analytics When not coding: exploring Sydney, working on side projects, and teaching tech to anyone who'll listen.

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:

  1. Base Case β†’ When to stop (the smallest doll)
  2. 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.

More from this blog

esreekarreddy

132 posts