Recursion · 1 / 18 Theory

What is recursion

Recursion is a technique in which a function calls itself to solve a problem by dividing it into smaller versions of the same problem. It sounds strange, but it is a natural way of thinking about many situations.

An everyday idea

Imagine you want to know how many people are in a queue and you can only ask the person in front: "how many people are there from you to the front?". Each person asks the next one and waits for the answer, and adds one. The first in the queue, the one with nobody ahead, answers "1". The answers come back adding up.

The two parts of every recursive function

  • Base case: the simplest version of the problem, which is solved directly, without calling itself again.
  • Recursive case: the function calls itself with a smaller problem, and uses that result to build its own.

A first example: countdown

def countdown(n):
    if n == 0:                  # base case
        print("Liftoff!")
        return
    print(n)
    countdown(n - 1)            # recursive case: a smaller problem

countdown(3)
# 3
# 2
# 1
# Liftoff!

An example that returns a value: sum from 1 to n

The sum from 1 to n is n plus the sum from 1 to n - 1. And the sum from 1 to 0 is 0:

def sum_to(n):
    if n == 0:                  # base case
        return 0
    return n + sum_to(n - 1)    # recursive case

print(sum_to(4))   # 10

What happens inside: the call stack

Each call waits for the next one. Python stacks them and, on reaching the base case, resolves them from the bottom up:

sum_to(4)
= 4 + sum_to(3)
= 4 + (3 + sum_to(2))
= 4 + (3 + (2 + sum_to(1)))
= 4 + (3 + (2 + (1 + sum_to(0))))
= 4 + (3 + (2 + (1 + 0)))     ← base case
= 4 + (3 + (2 + 1))
= 4 + (3 + 3)
= 4 + 6
= 10

With this same scheme you solve Calculate the factorial of a number (where multiplication replaces addition) and Create a recursive function to multiply.

Without a base case, there is no end

def endless(n):
    return endless(n + 1)   # never stops

endless(0)
# RecursionError: maximum recursion depth exceeded

Each call takes up memory. Python protects the program by cutting the calls when there are too many (around 1000) with a RecursionError. If you get this error, most likely the base case is missing or the problem does not get smaller on each call.