Recursion & Divide and Conquer in Python
Chapter 42: Recursion & Divide and Conquer
4 short lessons, with 3D animations, quizzes and coding tasks.
The lessons
Recursion again: the call stack, frame by frame
A recursive function solves a problem by calling itself on a smaller version of the same problem, and Python keeps one frame per unfinished call on the call stack until each call gets its answer.
Recursion trees and their cost: memoization
Draw every call as a node under the call that made it; the total work is the number of nodes, and when the same call appears more than once, remembering its first answer (memoization) removes every repeat.
Divide and conquer: split, solve, combine
Split the problem into smaller parts of the same kind (usually two halves), solve each part with the same function, then combine the parts' answers into the whole answer.
Reading the cost of a recursion: level by level
To find a recursion's cost, draw its tree, write beside each call the work it does itself (not counting its calls), add the work up level by level, and multiply by the number of levels.