Divide and conquer: split, solve, combine
🌍 In real life. Sixteen schools enter the district football cup. Nobody plays every other team: the draw splits the schools into two halves, each half finds its best team the same way, round after round, and the two winners meet in the final. One big question, "who is the best of sixteen?", becomes two smaller questions of exactly the same kind, and a single match puts their answers together.
That is divide and conquer, the idea behind binary search (Chapter 43) and the fast sorts (Chapter 45).
The idea in one sentence: 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.
Its words:
- divide: split the input, here at
mid = len(s) // 2intos[:mid]ands[mid:] - conquer: solve each part recursively; a part small enough to answer at once is the base case (one player has won their part)
- combine: build the whole answer from the parts' answers (one match: the better of two winners)
Step by step:
- one player? They are the winner: return them
- split the players into two halves
- find each half's winner with the same function
- the two winners play: return the better one
The recursion goes depth first, but the matches are the same as a cup played round by round. Watch it split down, then play up:
Why it is correct. The strongest player overall is in one of the two halves, so they win that half; in the final they beat the other half's winner, because they are stronger than everyone. The base case is right too: a lone player is the best of a part with one player. And every split makes the parts smaller, so the recursion ends.
What it costs, by counting.
- Matches: every match knocks exactly one player out, and all but one must go: n − 1 matches, for any way of splitting. That is the same as checking the players one by one. Halving does not make this problem cheaper.
- Depth: each split halves the parts, so the rounds are about log₂ n: 3 for 8 players, 10 for 1024. Going one player at a time recursively would be 1024 calls deep (a
RecursionError); halving is 10 deep. And the matches of one round don't depend on each other, so they could be played at the same time.
When halving does save work: solve once, use twice. To work out x to the power 1000, Chapter 17 multiplied by x a thousand times. But x¹⁰⁰⁰ = x⁵⁰⁰ × x⁵⁰⁰, and both halves are the same problem: work out x⁵⁰⁰ once, then square it (and for an odd power, multiply by x once more). 1000 → 500 → 250 → … → 1 → 0 is just 11 calls: O(log n) instead of O(n).
def champion(scores):
if len(scores) == 1: # one player: they won their part
return scores[0]
mid = len(scores) // 2
a = champion(scores[:mid]) # left half's winner
b = champion(scores[mid:]) # right half's winner
return a if a >= b else b # one match
def fast_power(x, n):
if n == 0:
return 1
half = fast_power(x, n // 2) # solve the half ONCE
if n % 2 == 0:
return half * half
return half * half * x
print(champion([3, 8, 5, 1, 9, 2, 7, 4]))
print(champion(list(range(5000)))) # only about 13 calls deep
print(fast_power(2, 10), fast_power(3, 5), fast_power(2, 1000) == 2 ** 1000)Mistakes and edge cases.
- a split that loses or repeats an item:
s[:mid]ands[mid + 1:]drops[mid]; the two halves must cover everything exactly once, likes[:mid]ands[mid:] - no base case for one item: with one player,
midis 0, the halves are[]and the same one player, and the recursion never ends - solving the same half twice: calling
fast_power(x, n // 2)twice and multiplying gives the right answer, but makes about 2n calls instead of log n; store the half in a variable - slicing copies: each
s[:mid]copies its half, so the cup above copies about n items per level; passingloandhiindexes instead avoids that (binary search does)
Quiz
What does this print?
def biggest(s): if len(s) == 1: return s[0] mid = len(s) // 2 a, b = biggest(s[:mid]), biggest(s[mid:]) print(a, b) return max(a, b) print(biggest([4, 9, 2, 6]))A knockout cup has 64 teams. How many matches are played?
- 63
- 6
- 32
- 64 × 63 / 2
And how many rounds does that cup of 64 teams take?
- 6
- 63
- 32
biggest([3, 7, 5]) gives 5, not 7. Which line is wrong?
def biggest(s): if len(s) == 1: return s[0] mid = len(s) // 2 return max(biggest(s[:mid]), biggest(s[mid + 1:]))fast_power(x, n) calls itself once, on n // 2. How many calls does fast_power(2, 1024) make?
- 12
- 1024
- 2048
Coding tasks
Write
champion(scores)as a knockout cup: split the list into two halves, find each half's best score withchampion, and return the better of the two. A part with one score is its own champion. It must work for 1500 players (too deep for one-at-a-time recursion).Write a recursive
fast_power(x, n): x to the power n for a whole number n ≥ 0, without**orpow, by halving: work out x to the power n // 2 once, square it, and multiply by x once more when n is odd.fast_power(2, 1000)must take only a few calls.