Video lecture
Watch on YouTube(opens in a new tab)Sub topic 12
Loop Invariants as a Correctness Tool
This chapter assumes you can read simple Python loops and that you know what a postcondition is from the earlier chapter on specifications. You checked correctness before by tracing examples. A trace shows that one input works. A loop invariant lets you argue that every valid input works.
What a Loop Invariant Is
A loop invariant is a statement about the program's variables that is true every time execution reaches the top of the loop. It holds before the first iteration and after each later one. A good invariant describes the partial progress the loop has made so far.
Here is find_max again with its invariant:
def find_max(xs):
# Precondition: xs is a non-empty list of comparable values
best = xs[0]
for x in xs[1:]:
# Invariant: best is the largest element seen so far
if x > best:
best = x
return best
print(find_max([3, 9, 2, 7])) # 9The Three-Part Argument
To use an invariant, you show three things:
- Initialization. The invariant is true before the first iteration.
- Maintenance. If the invariant is true at the start of an iteration, it is still true at the start of the next one.
- Exit. When the loop stops, the invariant together with the exit condition gives you the postcondition.
Applied to find_max:
| Part | Argument |
|---|---|
| Initialization | Only `xs[0]` has been seen, and `best = xs[0]`. |
| Maintenance | If `x > best`, `best` becomes `x`. If not, `best` was already at least `x`. Either way, `best` is the largest of the elements seen so far. |
| Exit | The loop has seen every element, so `best` is the largest element of `xs`. |
Notice that the precondition matters. If the list were empty, xs[0] would fail and initialization would have nothing to stand on.
An Invariant for Euclid's Algorithm
The loop in Euclid's algorithm changes a and b on every pass. The quantity that stays fixed is their greatest common divisor. If a0 and b0 are the original inputs, the invariant is gcd(a, b) == gcd(a0, b0).
- Initialization: at the start,
a = a0andb = b0. - Maintenance:
gcd(a, b) == gcd(b, a % b), because any number that divides bothaandbalso dividesa % b, and the reverse is also true. - Exit: the loop stops when
b == 0, andgcd(a, 0) == a. So the value returned equalsgcd(a0, b0).
You can check an invariant at run time while you are developing:
import math
def gcd(a, b):
a0, b0 = a, b
while b != 0:
assert math.gcd(a, b) == math.gcd(a0, b0)
a, b = b, a % b
return a
print(gcd(48, 18)) # 6An assertion only tests the inputs you actually run. The three-part argument covers every input.
Common Mistakes
- Invariant too weak. "best is an element of xs" is true throughout, but at exit it does not give you "best is the largest."
- Restating the loop. "best is updated when x > best" describes what the code does. It does not say what is true about the variables.
- Forgetting the exit step. Showing initialization and maintenance proves the invariant holds. It proves nothing about the output until you combine it with the exit condition.
- Ignoring termination. An invariant gives partial correctness, which means the answer is right if the loop stops. You still need the decreasing-measure argument from the previous chapter.
Exercise
A function sums a list with total = 0 followed by for i in range(len(xs)): total += xs[i]. State an invariant that holds at the top of each iteration, and show how it gives the postcondition total == sum(xs) when the loop ends.
Show answer
Invariant: at the top of the iteration with index i, total == sum(xs[0:i]). Initialization: when i = 0, total = 0 = sum of the empty slice. Maintenance: the body adds xs[i], so total == sum(xs[0:i+1]) at the top of the next iteration. Exit: after the last iteration, i has reached len(xs), so total == sum(xs[0:len(xs)]) == sum(xs).
Exercise
Someone proposes "a >= b" as the invariant for Euclid's loop. Why is it not enough to prove the result is the GCD, and is it even always true?
Show answer
It says nothing about the GCD, so at exit it cannot give the postcondition. It is also false at the start if the input has a < b, for example gcd(18, 48). The first iteration swaps the two values in that case.