本书暂未推出简体中文版。现有版本:English。
High School Computer Science · 10–12 年级
16Proving Algorithms Correct
A binary search passes every one of its ten tests. The next day, asked for a number that is not in the list, it never answers: the program runs until someone stops it. The tests were not wrong; they were too few, as tests always are. A test checks one input. To be sure of all the inputs, one needs an argument.
This chapter gives the two arguments that settle most loops. The first shows that a loop stops; the second, that what it computes is right. Both are short, both can be checked in the code itself with assert, and together they find the bug of the binary search above, and others like it, before any test does.
You already know
A while loop repeats its body as long as its condition is true (Book 1, grade 6). Linear search looks at each element in turn; binary search halves a sorted list at each step; selection sort and insertion sort put a list in order (Book 1, grade 8). A specification states what a function needs and what it promises, and an assertion stops the program if a condition is false (chapter 1). Euclid’s algorithm finds the greatest common divisor of two numbers by repeated remainders (mathematics, grade 9).
16.1 Does it stop?
A for loop over a list stops: it has as many turns as the list has elements. A while loop stops only if its condition becomes false, and nothing guarantees that it will.
Definition 16.1 (Variant, termination)
An algorithm has the property of termination if it stops on every input that meets its precondition. A variant of a loop is a whole number, computed from the variables, that is never negative while the loop runs and that strictly decreases at each turn.
A loop with a variant stops: a whole number that is at least and loses at least at each turn cannot do so more times than its first value. Euclid’s algorithm is an example. Its variant is : the new is the remainder a % b, which is smaller than and never negative.
def gcd(a, b):
"""Euclid; pre: a >= 0, b >= 0. Variant: b, a whole number that decreases."""
turn = 0
while b != 0:
print(f"turn {turn:2}: a={a:4} b={b:4}")
a, b = b, a % b # the new b is a % b, which is smaller than b
turn = turn + 1
print(f"turn {turn:2}: a={a:4} b={b:4} -> b = 0, the loop stops")
return a
print("gcd =", gcd(1071, 462))
print("gcd =", gcd(233, 144))
$ python variant_check.py
turn 0: a=1071 b= 462
turn 1: a= 462 b= 147
turn 2: a= 147 b= 21
turn 3: a= 21 b= 0 -> b = 0, the loop stops
gcd = 21
turn 0: a= 233 b= 144
turn 1: a= 144 b= 89
turn 2: a= 89 b= 55
turn 3: a= 55 b= 34
turn 4: a= 34 b= 21
turn 5: a= 21 b= 13
turn 6: a= 13 b= 8
turn 7: a= 8 b= 5
turn 8: a= 5 b= 3
turn 9: a= 3 b= 2
turn 10: a= 2 b= 1
turn 11: a= 1 b= 0 -> b = 0, the loop stops
gcd = 1
gcd(233, 144), from the run above: a staircase that only goes down, one step per turn, and cannot go below .The variant does not have to fall by each turn; it may fall by much more. What matters is that it falls by at least and starts from a finite value, which bounds the number of turns.
16.2 Is the answer right?
Definition 16.2 (Correct algorithm)
An algorithm is correct with respect to a specification if, on every input that meets the precondition, it stops and its result meets the postcondition.
Definition 16.3 (Loop invariant)
A loop invariant is a statement about the variables that is true before the first turn of a loop and that each turn keeps true: if it holds at the start of a turn, it holds at the end.
An invariant is then true when the loop stops, together with the negation of the loop’s condition. A good invariant is chosen so that these two facts, put together, give the postcondition.
Method 16.4 (Proving a loop with an invariant)
- Write the invariant, often “the part already handled is right”, with the loop’s index.
- Start: show that it is true before the first turn.
- Keep: suppose it is true at the start of a turn; show that it is still true after the turn.
- End: add the fact that the loop’s condition is false; deduce the postcondition.
- Give a variant, to show that the end is reached.
The function largest returns the largest element of a list. Its invariant is “best is the largest of t[:i]”. Start: with i = 1, t[:1] holds only t[0], which is best. Keep: if t[i] is larger than best, it becomes best, otherwise best stays; either way it is the largest of t[:i + 1], and i grows by one. End: the loop stops when i equals len(t), so t[:i] is the whole list. Variant: len(t) - i.
def largest(t):
"""Pre: t is a non-empty list of numbers. Post: returns the largest element of t."""
best = t[0]
i = 1
while i < len(t):
assert best == max(t[:i]) # invariant: best is the largest of t[:i]
if t[i] > best:
best = t[i]
i = i + 1
assert i == len(t) and best == max(t) # at the end: i == len(t), so t[:i] is t
return best
print(largest([31, 7, 58, 12, 58, 3]))
print(largest([-4]))
$ python largest.py
58
-4
An assertion of the invariant does not prove it; it checks it on the inputs that are run, and stops the program at the first turn where it fails, which points at the bug. The proof covers all the inputs; the assertion catches the gap between the proof and the code.
16.3 Selection sort
Selection sort finds a smallest element of the part not yet sorted and swaps it to the front of that part. Its invariant has two halves: t[:i] is sorted, and no element of t[:i] is larger than an element of t[i:].
def check(t, i):
"""The invariant: t[:i] is sorted, and nothing in t[:i] is larger than t[i:]."""
assert all(t[k] <= t[k + 1] for k in range(i - 1))
assert i == 0 or i == len(t) or t[i - 1] <= min(t[i:])
def selection_sort(t):
for i in range(len(t)):
check(t, i)
m = i # find the index m of a smallest element of t[i:]
for j in range(i + 1, len(t)):
if t[j] < t[m]:
m = j
t[i], t[m] = t[m], t[i] # move it to place i
print(f"turn {i}: {t[:i + 1]} | {t[i + 1:]}")
check(t, len(t))
selection_sort([29, 12, 47, 3, 18, 12])
$ python selection_sort.py
turn 0: [3] | [12, 47, 29, 18, 12]
turn 1: [3, 12] | [47, 29, 18, 12]
turn 2: [3, 12, 12] | [29, 18, 47]
turn 3: [3, 12, 12, 18] | [29, 47]
turn 4: [3, 12, 12, 18, 29] | [47]
turn 5: [3, 12, 12, 18, 29, 47] | []
t[:i + 1], sorted after the turn, from the rest.Start: with i = 0, t[:0] is empty, and both halves hold. Keep: the turn puts in place i a smallest element of t[i:]. By the second half, it is at least as large as everything in t[:i], so the first i + 1 elements are sorted; being a smallest of t[i:], it is no larger than anything left in t[i + 1:]. End: with i = len(t), the whole list is sorted. The swap only exchanges two elements, so the list keeps the same elements. Variant of the outer loop: len(t) - i; the inner loop is a for loop and stops.
16.4 Insertion sort
Insertion sort takes the elements one by one and slides each into place among those before it, which are already sorted. It has two loops, and each has its own invariant.
def insertion_sort(t):
for i in range(1, len(t)):
assert all(t[k] <= t[k + 1] for k in range(i - 1)) # outer: t[:i] is sorted
x = t[i]
j = i
while j > 0 and t[j - 1] > x:
# inner: t[j + 1:i + 1] holds elements larger than x, moved one place right
t[j] = t[j - 1]
j = j - 1
t[j] = x
print(f"turn {i}: {t[:i + 1]} | {t[i + 1:]} ({x} went to place {j})")
insertion_sort([29, 12, 47, 3, 18, 12])
$ python insertion_sort.py
turn 1: [12, 29] | [47, 3, 18, 12] (12 went to place 0)
turn 2: [12, 29, 47] | [3, 18, 12] (47 went to place 2)
turn 3: [3, 12, 29, 47] | [18, 12] (3 went to place 0)
turn 4: [3, 12, 18, 29, 47] | [12] (18 went to place 2)
turn 5: [3, 12, 12, 18, 29, 47] | [] (12 went to place 2)
The outer invariant is “t[:i] is sorted”. The inner invariant, for the while loop, is: the elements of t[j + 1:i + 1] are larger than , in order, and putting in place j would give the old t[:i] with added. Each inner turn moves one larger element right and lowers j; the inner loop stops when j is or when t[j - 1] is not larger than . In both cases , written in place j, is not smaller than what comes before it and is smaller than what comes after: t[:i + 1] is sorted, and the outer invariant is kept. The inner variant is j, the outer one len(t) - i.
16.5 Binary search
Binary search finds x in a sorted list by keeping a window t[lo:hi] outside of which x cannot be, and halving it.
def search(t, x):
"""Pre: t is sorted. Post: an index i with t[i] == x, or None if x is not in t."""
lo, hi = 0, len(t)
while lo < hi:
# invariant: x is neither in t[:lo] nor in t[hi:]; variant: hi - lo
mid = (lo + hi) // 2
print(f" lo={lo} mid={mid} hi={hi}")
if t[mid] == x:
return mid
if t[mid] < x:
lo = mid + 1
else:
hi = mid
return None
t = [3, 8, 12, 15, 21, 30, 34, 41, 47, 52]
for x in [41, 3, 20]:
print("search", x)
print("->", search(t, x))
$ python binary_search.py
search 41
lo=0 mid=5 hi=10
lo=6 mid=8 hi=10
lo=6 mid=7 hi=8
-> 7
search 3
lo=0 mid=5 hi=10
lo=0 mid=2 hi=5
lo=0 mid=1 hi=2
lo=0 mid=0 hi=1
-> 0
search 20
lo=0 mid=5 hi=10
lo=0 mid=2 hi=5
lo=3 mid=4 hi=5
lo=3 mid=3 hi=4
-> None
None.mid. The third mid holds .The invariant: x is neither in t[:lo] nor in t[hi:]. Start: both are empty. Keep: if t[mid] < x, then, the list being sorted, every element of t[:mid + 1] is less than x, so lo = mid + 1 keeps the invariant; if t[mid] > x, every element of t[mid:] is larger, and hi = mid keeps it. End: if the loop stops with lo >= hi, the window is empty, and by the invariant x is nowhere: None is right. The variant is hi - lo: mid lies in the window, so both lo = mid + 1 and hi = mid make it smaller.
The variant is where the opening bug hides. Writing lo = mid keeps the invariant, but not the variant: when hi = lo + 1, mid equals lo, and lo = mid changes nothing.
def search(t, x, cap=50):
lo, hi = 0, len(t)
turns = 0
while lo < hi:
turns = turns + 1
if turns > cap: # a guard for this demonstration only
raise RuntimeError(f"no end after {cap} turns: lo={lo}, hi={hi}")
mid = (lo + hi) // 2
if t[mid] == x:
return mid
if t[mid] < x:
lo = mid # the bug: mid was already compared
else:
hi = mid
return None
t = [3, 8, 12, 15, 21, 30, 34, 41, 47, 52]
for x in t:
assert search(t, x) == t.index(x)
print("all", len(t), "tests pass")
try:
print(search(t, 20))
except RuntimeError as error:
print("RuntimeError:", error)
$ python binary_search_bug.py
all 10 tests pass
RuntimeError: no end after 50 turns: lo=3, hi=4
lo=3, hi=4.History — Meaning given to programs
The idea of attaching statements to the points of a program and proving that each step keeps them true was published by Robert W. Floyd in 1967, for flowcharts. In 1969, C. A. R. Hoare turned it into rules for reasoning about the instructions of a programming language, one rule per kind of instruction, the loop rule resting on an invariant.
16.6 Exercises
Exercise 16.1 ★
Write the list [5, 2, 9, 1, 7] after the first two turns of selection sort.
Solution
Solution of Exercise 16.1.
Turn swaps the smallest, , into place : [1, 2, 9, 5, 7]. Turn finds already in place : the list stays [1, 2, 9, 5, 7].
Exercise 16.2 ★
Give a variant of the loop while n > 0: n = n - 2, for n a whole number, and say why it is one.
Solution
Solution of Exercise 16.2.
n itself, if n starts at or more: it falls by at each turn, and the loop runs only while n > 0, so during the loop it is a whole number at least . (If n starts odd, it ends at ; the variant only has to be non-negative while the loop runs.)
Exercise 16.3 ★
Give the values of lo, mid and hi at each turn when the chapter’s search looks for in the list of the output.
Solution
Solution of Exercise 16.3.
lo=0 mid=5 hi=10: ; lo=6 mid=8 hi=10: ; lo=9 mid=9 hi=10: found, the answer is .
Exercise 16.4 ★
For the loop s = 0, then for i in range(len(t)): s = s + t[i], is the statement “s is the sum of t[:i]” true before the first turn?
Solution
Solution of Exercise 16.4.
Yes: before the first turn i is in the statement, t[:0] is empty, its sum is , and s is .
Exercise 16.5 ★
A student writes largest with for i in range(1, len(t) - 1). On [4, 9, 2, 11] it returns . Which step of the proof fails?
Solution
Solution of Exercise 16.5.
The end step. The invariant still holds at each turn, but the loop stops at i = len(t) - 1, so it only gives “best is the largest of t[:len(t) - 1]”: the last element is never looked at, and is missed.
Exercise 16.6 ★★
Prove that this loop stops for every whole number n, by giving a variant: while n > 1, if n is even, n = n // 2, otherwise n = n - 1.
Solution
Solution of Exercise 16.6.
n is a variant. Inside the loop n > 1; then n // 2 and n - 1 are both whole numbers smaller than n and at least . So n stays non-negative and strictly decreases: the loop stops.
Exercise 16.7 ★★
Write index_of_min(t, i) that returns the index of a smallest element of t[i:], ending with an assert of its postcondition.
Solution
Solution of Exercise 16.7.
def index_of_min(t, i):
m = i
for j in range(i + 1, len(t)):
if t[j] < t[m]:
m = j
assert i <= m < len(t) and t[m] == min(t[i:])
return m
The invariant of the loop is “t[m] is a smallest element of t[i:j]”.
Exercise 16.8 ★★
In the chapter’s search, a student writes hi = mid - 1. The loop always stops, but on the list of the output it misses , and . Which part of the proof fails, and why?
Solution
Solution of Exercise 16.8.
The keep step of the invariant. When t[mid] > x, every element of t[mid:] is larger than x, but t[mid - 1] may be x; hi = mid - 1 puts it outside the window, so “x is not in t[hi:]” becomes false. The variant still falls, which is why the loop stops, with a wrong answer.
Exercise 16.9 ★★
Prove, with an invariant, that the loop of exercise 16.4 computes the sum of t.
Solution
Solution of Exercise 16.9.
Invariant: at the start of the turn for i, s is the sum of t[:i]. Start: exercise 16.4. Keep: the turn adds t[i], so s becomes the sum of t[:i + 1], which is the invariant for the next i. End: after the last turn, i has gone through len(t) - 1, so s is the sum of t[:len(t)], the whole list. A for loop over a range stops.
Exercise 16.10 ★★
Write a loop that counts the occurrences of x in t, and state the invariant that proves it.
Solution
Solution of Exercise 16.10.
c = 0
for i in range(len(t)):
if t[i] == x:
c = c + 1
Invariant: at the start of the turn for i, c is the number of occurrences of x in t[:i]. The turn adds exactly when t[i] is x, so it is kept; at the end c counts the whole list.
Exercise 16.11 ★★
Write is_sorted(t) with one loop that compares neighbours, and prove it correct: it returns True exactly when t is sorted.
Solution
Solution of Exercise 16.11.
def is_sorted(t):
for i in range(1, len(t)):
if t[i - 1] > t[i]:
return False
return True
Invariant: at the start of the turn for i, t[:i] is sorted. It holds for i = 1, a single element. If t[i - 1] > t[i], the list is not sorted and False is right; otherwise t[i] is not smaller than the last element of the sorted t[:i], so t[:i + 1] is sorted. If the loop ends without returning, t[:len(t)] is sorted and True is right. An empty list or a list of one element skips the loop and is sorted.
Exercise 16.12 ★★★
Write out in full the proof that insertion sort sorts its list: the outer invariant, the inner invariant, why the inner loop keeps it, and why both loops stop.
Solution
Solution of Exercise 16.12.
Outer invariant: at the start of turn i, t[:i] holds the first i elements of the original list, sorted, and t[i:] is unchanged. Start: t[:1] has one element. Inner invariant, with the old t[i]: t[:j] is unchanged and sorted, t[j + 1:i + 1] holds the old t[j:i], every element of which is larger than . It holds when j = i, both slices being as they were. An inner turn copies t[j - 1], larger than , into place j and lowers j: kept. The inner loop stops, j being a variant that is at least . When it stops, either j = 0, or t[j - 1] <= x; writing in place j puts it after elements not larger than it and before elements larger than it: t[:i + 1] is sorted and holds the old t[:i] and . The outer invariant is kept; at the end, i reaches len(t) and the whole list is sorted. The outer loop is a for loop and stops.
Exercise 16.13 ★★★
Prove that the chapter’s search returns an index of x whenever x is in the list.
Solution
Solution of Exercise 16.13.
Let be an index with t[p] == x. By the invariant, x is not in t[:lo] nor in t[hi:], so always lies in the window: lo <= p < hi, and the window is never empty. The loop condition lo < hi therefore stays true, and the only way out is the return mid, which happens only when t[mid] == x. Since the variant hi - lo forces the loop to stop, the function does return, and what it returns is an index of x.
Exercise 16.14 ★★★
The loop while n != 1, with n = n // 2 if n is even and n = 3 * n + 1 otherwise, stops for every n anyone has tried; from it takes turns. Why do neither n nor the number of turns left serve as a variant? What would a proof that it always stops need?
Solution
Solution of Exercise 16.14.
n does not always fall: an odd n becomes 3 * n + 1, much larger. “The number of turns left” falls by one each turn, but it is a whole number only if the loop stops, which is what was to be proved: using it assumes the result. A proof would need some quantity, computed from n, that never becomes negative and falls at each turn, or a different argument altogether. Nobody has found one: whether this loop stops for every n is an open question, though every number tried so far reaches .
Exercise 16.15 ★★★
A function f gives False on lo, lo + 1, … up to some point, then True up to hi - 1. Write first_true(f, lo, hi) that returns the first number where f is true, or hi if there is none, by halving, with its invariant and its variant.
Solution
Solution of Exercise 16.15.
def first_true(f, lo, hi):
while lo < hi:
mid = (lo + hi) // 2
if f(mid):
hi = mid
else:
lo = mid + 1
return lo
Invariant: f is false on every number from the first lo to the present lo excluded, and true from the present hi to the first hi excluded. A true f(mid) makes f true from mid on, by the precondition; a false one makes it false up to mid. At the end lo == hi: everything before is false, everything from there is true, so lo is the first true, or the first hi if none is. Variant: hi - lo, which both branches lower since lo <= mid < hi.
16.7 Problem: The Integer Square Root
Problem 16.1
Weekend problem — an integer square root, proved and timed
The integer square root of a whole number is the largest whole number such that : for it is , for it is . The program below computes it twice, by counting up from and by halving a window, and counts the turns of each.
"""The weekend problem: the integer square root, by counting up and by halving."""
import math
def isqrt_linear(n):
r, turns = 0, 0
while (r + 1) * (r + 1) <= n: # variant: n - r * r
r, turns = r + 1, turns + 1
return r, turns
def isqrt_halving(n):
lo, hi, turns = 0, n + 1, 0
while hi - lo > 1: # invariant: lo * lo <= n < hi * hi
mid = (lo + hi) // 2
if mid * mid <= n:
lo = mid
else:
hi = mid
turns = turns + 1
return lo, turns
for n in [0, 1, 15, 16, 17, 1000]:
print(f"n = {n:4}: linear {isqrt_linear(n)}, halving {isqrt_halving(n)}")
N = 10**6
worst, first = 0, None
for n in range(N + 1):
r, turns = isqrt_halving(n)
assert r == math.isqrt(n)
if turns > worst:
worst, first = turns, n
print(f"0 <= n <= {N}: halving always right,"
f" at most {worst} turns (first at n = {first})")
print(f"linear at n = {N}: {isqrt_linear(N)[1]} turns")
$ python isqrt.py
n = 0: linear (0, 0), halving (0, 0)
n = 1: linear (1, 1), halving (1, 1)
n = 15: linear (3, 3), halving (3, 4)
n = 16: linear (4, 4), halving (4, 4)
n = 17: linear (4, 4), halving (4, 4)
n = 1000: linear (31, 31), halving (31, 9)
0 <= n <= 1000000: halving always right, at most 20 turns (first at n = 555007)
linear at n = 1000000: 1000 turns
Part I — The specification.
- Write the precondition and the postcondition of an integer square root function.
- Show that meets the postcondition exactly when .
- Give the integer square roots of , , , and .
- Why does such an exist, and why only one?
Part II — Counting up.
- State an invariant of the loop of
isqrt_linearthat, at the end, gives the postcondition. - Prove that it holds at the start and is kept.
- Show that
n - r * ris a variant. - How many turns does it take for ? For ?
Part III — Halving.
- Check that
lo * lo <= n < hi * hiholds before the first turn. - Show that each turn keeps it, in each of the two branches.
- Show that at the end
lomeets the postcondition. - Show that
midalways lies strictly betweenloandhiinside the loop. - Deduce a variant, and that the loop stops.
Part IV — How many turns.
- Follow the turns of
isqrt_halving(15)and check the count printed. - Show that if
hi - lois at most at the start of a turn, it is at most at the end. - Deduce that for , the loop makes at most turns.
- Compute ; deduce a bound on the turns for .
- Compare with the run: maximum and first reaching it. Why is the first such not ?
- What does the line
assert r == math.isqrt(n)add to the proof, and what does the proof add to it? - State the result: correctness, termination and the number of turns, against counting up.
Solution
Solution of Problem 16.1.
1. Precondition: is a whole number, . Postcondition: is a whole number, , and no larger whole number has its square at most .
2. For , the squares grow with . So if , every number above has a square above , and is the largest; conversely the largest has .
3. , , , , .
4. has , so there is at least one candidate; a candidate has , so there are finitely many. Their largest exists and is unique.
5. . When the loop stops, its condition is false: , and with question 2 that is the postcondition.
6. Start: and . Keep: a turn runs only if , and then sets to , whose square is at most .
7. By the invariant, n - r * r is at least ; each turn raises by one, so grows by and n - r * r falls by at least .
8. One turn per value of above : as many turns as the result, for , as printed.
9. lo = 0 and ; hi = n + 1 and .
10. If mid * mid <= n, then lo = mid has its square at most , and hi does not change. Otherwise , and hi = mid keeps .
11. At the end hi - lo <= 1. By the invariant , so lo < hi, hence hi = lo + 1 and : the postcondition, by question 2.
12. Inside the loop hi - lo >= 2, so , and rounding down keeps mid between lo + 1 and hi - 1.
13. hi - lo is a whole number, at least inside the loop; each turn replaces lo or hi by mid, strictly between them, so it strictly falls. The loop stops.
14. lo=0, hi=16: mid=8, , hi=8; mid=4, , hi=4; mid=2, , lo=2; mid=3, , lo=3; now hi - lo = 1. Four turns, result , as printed.
15. The new window is mid - lo or hi - mid; these two add up to hi - lo and differ by at most , so the larger is at most half of hi - lo rounded up. Half of is , already whole.
16. The window starts at . After one turn it is at most , after two at most , and after turns at most , where the loop stops: at most turns.
17. : at most turns for .
18. The run finds turns at most, first at . For the bound gives ; just above, turns are possible but not forced: whether the window shrinks to the half rounded down or rounded up depends on the branch taken, and only from do enough halvings round up.
19. The assertion compares a million results with Python’s own function, an independent computation: it would catch a slip between the code and the proof, such as a wrong sign. The proof covers every , beyond too, and termination, which no test run can show.
20. The integer square root by halving is correct for every whole and always stops; for it takes at most turns, reached first at , where counting up takes up to .