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
- Base case: the smallest version, answered directly with no more calls. ("I'm first, my place is 1.")
- 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.
def factorial(n):
if n <= 1: # base case
return 1
return n * factorial(n - 1) # recursive caseCall stack (newest on top)
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
- Trust that the function already works for smaller inputs.
- Find the base case: the input so small the answer is obvious (0, 1, an empty list, an empty string).
- 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
Quiz score: 0 of 3
Exercises solved: 0 of 2
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.