Module 6 · Recursion, Backtracking and Divide and Conquer · Lesson 19 of 40

Recursion: a function that calls itself

Solve a big problem by solving a smaller copy of it, with a base case that stops the calls.

In this lesson · about 22 minutes

  • Name the base case and the recursive case of a function
  • Follow the call stack as calls wait and return
  • Write simple recursive functions

Imagine a queue of people, and you want to know your place in it. You ask the person in front: "What is your place?" They ask the person in front of them, and so on. The first person says "1". Then each answer comes back down the line, plus one. That is recursion: solving a problem by asking a smaller copy of the same question.

Two parts, always

  1. Base case: the smallest version, answered directly with no more calls. ("I'm first, my place is 1.")
  2. Recursive case: call the function on a smaller input, then use its answer.
def factorial(n):           # 5! = 5 × 4 × 3 × 2 × 1
    if n <= 1:              # base case
        return 1
    return n * factorial(n - 1)   # recursive case

Without a base case, the calls never stop. Python gives up with a RecursionError (too many waiting calls). This is called infinite recursion.

The call stack

Each call has to wait for the smaller call to finish. Python keeps the waiting calls on the call stack (a stack, from Module 5!). The deepest call finishes first, and the answers flow back up.

Try it · see it work

Watch the call stack

Step through factorial. Watch calls pile up until the base case, then return one by one.

n =
def factorial(n):
    if n <= 1:          # base case
        return 1
    return n * factorial(n - 1)   # recursive case

Call stack (newest on top)

factorial(4) waiting…

Step 1 of 9factorial(4) needs factorial(3) first, so it waits and a new call goes on top of the stack.

Three steps to write any recursive function

  1. Trust that the function already works for smaller inputs.
  2. Find the base case: the input so small the answer is obvious (0, 1, an empty list, an empty string).
  3. Shrink and combine: call the function on a smaller input and build your answer from it.

Example: the sum of a list is "the first number + the sum of the rest". The sum of an empty list is 0.

def total(nums):
    if not nums:
        return 0
    return nums[0] + total(nums[1:])

Cost

Time = number of calls × work per call. Space = the deepest the call stack gets. factorial(n) makes n calls, each O(1), so it is O(n) time and O(n) space.

Try it: countdown and power

Exercise

Add up the digits

Write a recursive function digit_sum(n) that adds up the digits of a non-negative whole number. digit_sum(472) is 4 + 7 + 2 = 13. Hint: n % 10 is the last digit and n // 10 drops it.

Exercise

Fibonacci numbers

The Fibonacci numbers go 0, 1, 1, 2, 3, 5, 8, 13… Each is the sum of the two before. Write a recursive fib(n) with fib(0) = 0 and fib(1) = 1.

Check your understanding0 of 3 correct

Question 1

1.What stops a recursive function from calling itself forever?

Question 2

2.factorial(4) calls factorial(3). What does factorial(4) do meanwhile?

Question 3

3.A recursive function goes n calls deep. Its extra space is…

Quiz score: 0 of 3

Exercises solved: 0 of 2

Tip: answer every quiz question correctly first.

Noviq Academy is free and for learning. This course follows the topics of a set of DSA study notes, rewritten in Noviq's own words with Python examples. Python runs in your own browser with Pyodide; nothing you type is sent to Noviq.