Video lecture
Watch on YouTube(opens in a new tab)Sub topic 10
Does It Solve the Problem? Checking Correctness
This chapter assumes you can read short Python functions. It also assumes you know what a specification is: inputs, outputs, a precondition and a postcondition, as defined earlier in the tutorial. You should also be able to trace a loop by hand with a state table. The chapter shows what it means for an algorithm to be correct, how to check correctness with tests and with arguments, and the usual ways those checks go wrong.
What "correct" means
An algorithm is never just correct. It is correct with respect to a specification. The specification is a contract:
- If the input satisfies the precondition,
- then the algorithm produces an output that satisfies the postcondition.
The contract promises nothing about inputs that break the precondition. Euclid's algorithm requires a >= 0, b >= 0, not both zero. When you call gcd(0, 0) it returns 0. That result is not a bug, because the input lies outside the contract. Calling gcd(-4, 6) breaks the contract in the same way. Any result is allowed there, because the caller broke the agreement first.
The rule also runs the other way. An output that "looks right" is not enough. It counts as correct only if it meets every clause of the postcondition, for every input the precondition allows.
Partial and total correctness
People who check correctness separate two claims:
| Claim | Meaning | Who handles it |
|---|---|---|
| Partial correctness | *If* the algorithm stops, its output satisfies the postcondition | This chapter |
| Termination | The algorithm stops on every valid input | The next chapter |
| Total correctness | Both of the above | Both together |
Keeping them apart lets you argue about each one alone. A loop that never ends is partially correct by default, because it never produces a wrong answer. That is why partial correctness alone is too weak to be useful.
The postcondition is your test oracle
An oracle is a way to decide whether an output is right. A test usually compares the result with a value you worked out by hand, such as gcd(48, 18) == 6. That works, but it only covers inputs you have already solved. A stronger approach checks the postcondition itself.
The postcondition for GCD says: g divides a, g divides b, and no larger integer divides both. You can turn that sentence into code and run it on every small input:
def gcd(a, b):
while b != 0:
a, b = b, a % b
return a
def satisfies_gcd_spec(a, b, g):
"""Check the postcondition: g is the greatest common divisor of a and b."""
if g <= 0:
return False
if a % g != 0 or b % g != 0:
return False
# No integer larger than g may divide both a and b.
for d in range(g + 1, max(a, b) + 1):
if a % d == 0 and b % d == 0:
return False
return True
checked = 0
for a in range(0, 40):
for b in range(0, 40):
if a == 0 and b == 0:
continue # violates the precondition, so it is not tested
g = gcd(a, b)
assert satisfies_gcd_spec(a, b, g), (a, b, g)
checked += 1
print(f"{checked} valid inputs checked, all satisfy the postcondition")Running it prints 1599 valid inputs checked, all satisfy the postcondition. The oracle is slow, but that doesn't matter here. Its only job is to be obviously right, so you can trust it more than the fast algorithm under test.
Testing finds bugs; arguments rule them out
Exhaustive checking over 0 to 39 is convincing, but it is not a proof. The precondition allows infinitely many inputs, and a test only covers the ones you ran. Edsger Dijkstra's point still holds: testing can show that bugs are present, but it cannot show that they are absent.
A correctness argument covers every valid input at once. For Euclid's algorithm the argument rests on one fact: for b > 0, the common divisors of (a, b) are exactly the common divisors of (b, a mod b). Each loop iteration therefore keeps the GCD unchanged. When the loop exits, b is 0. Since gcd(a, 0) = a, the returned a is the answer. A property that every iteration preserves is called a loop invariant. A later chapter covers loop invariants as a technique of their own.
In practice you use both:
Hunting for counterexamples
A counterexample is one valid input on which the output breaks the postcondition. One counterexample is enough to prove an algorithm incorrect. The best way to find one is to read the precondition and look for its boundaries, rather than trying inputs at random.
Here is a broken version of find_max:
def find_max_buggy(xs):
# Precondition: xs is a non-empty list of comparable values
best = 0
for x in xs:
if x > best:
best = x
return best
def satisfies_max_spec(xs, result):
# Postcondition: result is an element of xs and no element exceeds it
return result in xs and all(x <= result for x in xs)
for case in [[3, 9, 2], [5], [-3, -1, -7]]:
r = find_max_buggy(case)
print(case, r, satisfies_max_spec(case, r))Output:
[3, 9, 2] 9 True
[5] 5 True
[-3, -1, -7] 0 FalseThe precondition allows negative numbers, and the buggy version assumes the values are at least 0. The returned 0 is not even an element of the list. The correct version starts with best = xs[0], which uses the "non-empty" part of the precondition. You can find boundary cases like these by asking what each clause of the precondition allows:
- The smallest legal sizes: a list of one element, or
b = 0. - Extreme values: negatives, zero, duplicates, and the largest or smallest element in first or last position.
- Inputs where two branches meet:
a == b,a < b, equal elements.
For example, gcd(18, 48) with a < b still works. The first iteration just swaps the arguments, since 18 mod 48 = 18. A trace confirms this.
When the specification itself is wrong
Correctness only goes as far as the specification. If the postcondition is too weak, a useless algorithm can still be "correct". Suppose a sort is specified as "the output list is in non-decreasing order":
def lazy_sort(xs):
return []
def weak_sort_spec(xs, out):
return all(out[i] <= out[i + 1] for i in range(len(out) - 1))
def full_sort_spec(xs, out):
return weak_sort_spec(xs, out) and sorted(xs) == sorted(out)
data = [4, 1, 3]
print(weak_sort_spec(data, lazy_sort(data))) # True
print(full_sort_spec(data, lazy_sort(data))) # FalseThe empty list is ordered, so it passes the weak specification. The full specification adds that the output is a permutation of the input: the same elements, the same number of times. Using sorted inside an oracle for a sort is acceptable here, because the oracle only checks a fixed result. Its job is to be trustworthy, not original.
The fault can also go the other way. A specification that is too strong cannot be met at all, such as "return the maximum of any list, including an empty one". Either way, check the specification before you blame the algorithm.
Common errors
| Error | What goes wrong | Remedy |
|---|---|---|
| Testing only the worked example | Passes `gcd(48, 18)` and misses `b = 0` or `a < b` | Derive test inputs from each precondition clause |
| Testing invalid inputs as failures | Reports `gcd(0, 0) = 0` as a bug | Skip or reject inputs outside the precondition |
| Checking only part of the postcondition | Checks that `g` divides both inputs but not that it is the greatest | Turn every clause into code |
| Oracle reuses the algorithm | The same bug appears in both, so the test passes | Write a slow, direct oracle |
| Weak specification | `lazy_sort` counts as correct | Ask what a useless algorithm could get away with |
| Treating "it stopped and was right" as total correctness | Ignores inputs on which it never stops | Argue termination separately (next chapter) |
Exercises
Exercise
An algorithm is specified with precondition "n is an integer, n >= 1" and postcondition "returns the sum 1 + 2 + ... + n". It returns n * (n + 1) // 2 for n >= 1, and returns 5 for n = -3. Is it correct? Explain.
Show answer
Yes. For every input that satisfies the precondition, the formula gives the required sum. The input n = -3 breaks the precondition, so the specification promises nothing about it, and the result 5 is not a correctness failure.
Exercise
Write a Python function satisfiessearchspec(items, target, result) for linear search, whose postcondition is "if target is in items, result is the index of its first occurrence; otherwise result is -1". Then name a wrong implementation that a check of only "items[result] == target when result != -1" would accept.
Show answer
def satisfiessearchspec(items, target, result): return items.index(target) == result if target in items else result == -1. The weaker check accepts an implementation that returns the last match instead of the first. With items [7, 2, 7] and target 7, it returns 2, which matches but is not the first occurrence.
Exercise
A student specifies "remove duplicates" with the postcondition "no value appears twice in the output". Give an algorithm that meets this specification but is useless, and strengthen the postcondition.
Show answer
Always returning the empty list meets the specification. A stronger postcondition: the output contains no repeated value, and the set of values in the output equals the set of values in the input. If order matters, add that each value appears in the order of its first occurrence in the input.