Builds onBig-O and complexity
01The idea
A recursive function solves a problem by calling itself on a smaller version of the same problem. Every recursive function has two parts:
- The base case. The input is so small that you know the answer straight away. Return it without another call.
- The recursive case. Make the input smaller, call the function on it, and use the answer that comes back.
Each call must move closer to the base case. If it does not, the calls never stop.
When a function calls itself, the first call pauses. The computer keeps the paused call on the call stack, with its own copy of every local variable. The new call goes on top. When the top call returns, it comes off the stack, and the call below it continues from where it paused.
So recursion runs in two phases. On the way down, calls are added to the stack. On the way back up, each call takes the answer from the call above it and finishes its own work.
You do not have to trace every call to write a recursive function. Assume the smaller call returns the right answer. Then work out how to build your answer from it.
02How to spot it
Recursion fits when the problem contains smaller copies of itself:
- The data is nested: trees, folders inside folders, lists inside lists.
- You can build the answer for n from the answer for n - 1, or from a part of the input.
- The problem asks you to try every choice, such as every subset or every order. Each choice leads to a smaller problem.
- The problem splits in half and combines the halves, as merge sort does.
Watch the depth. Every open call uses stack memory. Python stops at about 1,000 nested calls by default. A recursion that goes 100,000 calls deep needs a loop instead.
Sign in to read the rest of this lesson
The worked example, the interactive visualization, the code template and a short quiz that marks the lesson as done in your study plans.
Sign in to continue