2.03

Recursion

Unlock the power of functions that call themselves. Master base cases, recursive calls, and classic recursive algorithms.

Learning Objectives:

  • β€’Understand the two parts of every recursive function (base case + recursive call)
  • β€’Implement recursive sum, power, and factorial
  • β€’Compute Fibonacci numbers recursively
  • β€’Calculate the sum of digits recursively
  • β€’Solve the Tower of Hanoi
Prerequisites: [object Object]
Estimated Time: 80 min

What is Recursion?

A recursive function is one that calls itself. Every recursive function has two essential parts:

  1. Base case β€” the condition where the function stops calling itself
  2. Recursive call β€” the function calling itself with a simpler input

Without a base case, the function would call itself forever (stack overflow!).

A Simple Example: Counting Down

python
def countdown(n): if n == 0: # base case print("Go!") else: print(n) countdown(n - 1) # recursive call with n-1 countdown(3) # 3 # 2 # 1 # Go!

Recursive Sum

Sum all integers from 1 to N:

plaintext
sum(5) = 5 + sum(4) = 5 + 4 + sum(3) = 5 + 4 + 3 + sum(2) = 5 + 4 + 3 + 2 + sum(1) = 5 + 4 + 3 + 2 + 1 + sum(0) = 5 + 4 + 3 + 2 + 1 + 0 = 15
python
def sum_to_n(n): if n == 0: # base case return 0 return n + sum_to_n(n - 1) # recursive call

Recursive Power

Compute x^n:

plaintext
power(2, 4) = 2 * power(2, 3) = 2 * 2 * power(2, 2) = 2 * 2 * 2 * power(2, 1) = 2 * 2 * 2 * 2 * power(2, 0) = 2 * 2 * 2 * 2 * 1 = 16
python
def power(x, n): if n == 0: # base case: anything^0 = 1 return 1 return x * power(x, n - 1)

The Call Stack

Each recursive call adds a frame to the call stack. When the base case is reached, the stack unwinds β€” each frame returns its value to the caller.

plaintext
power(2, 3) └─ 2 * power(2, 2) └─ 2 * power(2, 1) └─ 2 * power(2, 0) └─ 1 ← base case └─ 2 * 1 = 2 ← unwind └─ 2 * 2 = 4 └─ 2 * 4 = 8

The Tower of Hanoi

The classic puzzle: move N disks from peg A to peg C using peg B as auxiliary, never placing a larger disk on a smaller one.

The recursive insight:

  1. Move the top N-1 disks from A to B (using C)
  2. Move disk N from A to C
  3. Move the N-1 disks from B to C (using A)
python
def hanoi(n, source, target, auxiliary): if n == 1: print(f"Move disk 1 from {source} to {target}") return hanoi(n - 1, source, auxiliary, target) print(f"Move disk {n} from {source} to {target}") hanoi(n - 1, auxiliary, target, source)

For 3 disks, this produces 7 moves (2^n - 1 moves in general).

Watch Out for Stack Depth!

Python's default recursion limit is 1000. For very deep recursion (large N), an iterative approach is safer. For our exercises, inputs are small enough that recursion is fine.