Video lecture
Watch on YouTube(opens in a new tab)Sub topic 3
Does It Solve the Problem? Checking Correctness
This chapter assumes you can read simple Python, compute remainders with %, and write a problem specification with preconditions and postconditions.
Correctness Against a Specification
An algorithm is correct when every input that satisfies the precondition produces an output that satisfies the postcondition. Tracing a few inputs can expose bugs, but it cannot prove correctness, because you can only test a finite number of cases. To cover all inputs, you need an argument.
Does It Stop? Arguing Termination
A correct answer is useless if the algorithm never returns. To show that a loop terminates, find a decreasing measure. This is a non-negative integer that gets strictly smaller on every iteration. Such a value cannot decrease forever, so the loop must end. In Euclid's algorithm the measure is b: since a % b < b, each step replaces b with a smaller non-negative value.
Loop Invariants as a Correctness Tool
A loop invariant is a statement that holds before the loop starts and stays true after each iteration. When the loop exits, the invariant together with the exit condition should give you the postcondition.
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])) # 9Once every element has been seen, "largest seen so far" means the same as "largest element", which is the postcondition.
Describing Algorithms Recursively
A recursive description has two parts: a base case that returns directly, and a recursive case that calls itself on a smaller input. The termination argument is the same as for loops, applied to each call.
def gcd_recursive(a, b):
if b == 0:
return a
return gcd_recursive(b, a % b)
print(gcd_recursive(48, 18)) # 6How Much Work? Counting Steps and Big-O
To estimate cost, count the basic steps as a function of the input size n. Linear search does at most n comparisons, so it runs in O(n) time. Big-O drops constant factors and lower-order terms and keeps only the growth rate.
| Algorithm | Worst-case steps | Big-O |
|---|---|---|
| `find_max` | n − 1 comparisons | O(n) |
| `linear_search` | n comparisons | O(n) |
Choosing the Right Level of Detail
Pitch the description at its reader. "Find the largest element" is enough for a design discussion. Someone implementing the algorithm needs pseudocode, and anyone checking a correctness proof needs the invariants.
Exercise
For linear_search, state a loop invariant and a decreasing measure that together show it returns the correct result and terminates.
Show answer
Invariant: target does not appear in items[0..i-1]. Decreasing measure: len(items) - i, which falls by one each iteration and stays non-negative. If the loop finds a match, it returns i, the first match. If the loop finishes, the invariant covers the whole list, so returning -1 is correct.