Video lecture
Watch on YouTube(opens in a new tab)Sub topic 4
Stating the Problem Precisely: Inputs, Outputs and Conditions
This chapter assumes you can read simple Python, are comfortable with integer remainder (%), and already know the difference between a problem, an algorithm and a program from the previous chapter. In this chapter you will write down exactly what problem an algorithm is meant to solve, before you decide how it solves it.
A problem specification is a precise statement of what counts as a valid input and what counts as a correct output for that input. It has four parts:
| Part | Question it answers | Example for GCD |
|---|---|---|
| Inputs | What data does the algorithm receive, and of what type? | Two integers `a` and `b` |
| Outputs | What does it produce? | One integer `g` |
| Precondition | Which inputs is the algorithm required to handle? | `a >= 0`, `b >= 0`, not both zero |
| Postcondition | What must be true of the output, relative to the input? | `g` is the greatest common divisor of `a` and `b` |
The specification says nothing about loops, remainders or recursion. Euclid's algorithm, a brute-force search over candidate divisors, and a prime-factorisation method all meet the same specification. That independence is the point. The specification is the fixed target that later chapters measure correctness against.
The Specification as a Contract
A specification works like a contract between two parties. The caller promises to supply inputs that satisfy the precondition. In return, the algorithm promises that its output will satisfy the postcondition. If the caller breaks the precondition, the algorithm owes nothing: it may return garbage, crash, or loop forever, and it is still correct.
This split of responsibility explains why preconditions exist at all. Euclid's algorithm has no sensible answer for gcd(0, 0), since every integer divides zero and there is no greatest one. Rather than inventing a value, the specification excludes that input. The precondition "not both zero" moves the burden onto the caller.
Inputs and Outputs: Name Them and Give Them Types
Give every input and output a name and a domain, meaning the set of values it can take. "A list" is too vague. "A list xs of integers" is better. "A non-empty list xs of values that can be compared with <" is what find_max actually needs.
Names matter because the postcondition has to refer to them. You cannot write "the output is the largest element of the input" precisely unless the input and output have names. Compare:
- Vague: "Returns the biggest number."
- Precise: "Returns a value
msuch thatmis an element ofxs, andm >= xfor everyxinxs."
The precise version has two clauses. m is in the list, and m is at least as large as everything in the list. Both are needed. Drop the first, and a function returning float('inf') would satisfy the specification.
Postconditions Relate Output to Input
A postcondition has to mention the input. "The output is a positive integer" is a true statement about GCD results, but it is not a specification of GCD, because it does not say which positive integer. A useful postcondition is a relationship between the output and the original input values.
For GCD the full postcondition is:
g > 0gdividesaandgdividesb- No integer larger than
gdivides bothaandb
Each clause rules out a specific wrong answer. Clause 2 alone is satisfied by g = 1 for every input. Clause 3 is what forces the answer to be the greatest common divisor.
Making a Specification Executable
You can turn a postcondition into a Python function that checks it. This does not prove an algorithm correct, but it makes the specification unambiguous and lets you test any implementation against it.
def gcd_pre(a, b):
"""Precondition for GCD."""
return a >= 0 and b >= 0 and not (a == 0 and b == 0)
def gcd_post(a, b, g):
"""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 larger integer divides 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
def gcd(a, b):
while b != 0:
a, b = b, a % b
return a
def wrong_gcd(a, b):
return 1 # satisfies "divides both" but not "greatest"
for a in range(0, 30):
for b in range(0, 30):
if gcd_pre(a, b):
assert gcd_post(a, b, gcd(a, b)), (a, b)
print("gcd meets its specification on all tested inputs")
print("wrong_gcd(48, 18) passes?", gcd_post(48, 18, wrong_gcd(48, 18)))Running this prints that gcd passes and that wrong_gcd(48, 18) fails. Note the loop skips inputs where gcd_pre is false. Testing gcd(0, 0) would be testing outside the contract.
The checker is slow, since it tries every candidate divisor. That is acceptable, because a specification only needs to be clear. It does not need to be efficient. Often the clearest specification of a problem is itself a terrible algorithm.
Handling Ambiguity: Ties, Duplicates and "Not Found"
Many informal problem statements fall apart once you ask what happens in an unusual case. Linear search shows this well. "Find the target in the list" leaves several questions open:
- What if the target appears more than once?
- What if it does not appear at all?
- Is the result the element, a Boolean, or a position?
The linear_search function from this tutorial answers all three, and its specification should say so:
Inputs: a list items of length n; a value target
Output: an integer i
Precondition: values in items can be compared with target using ==
Postcondition:
If target occurs in items:
0 <= i < n, items[i] == target,
and items[j] != target for every j < i (i is the FIRST match)
Otherwise:
i == -1The clause "for every j < i" is what makes the result unique. Without it, any matching index would satisfy the specification. Sometimes that looser specification is what you want, because it gives implementers freedom, for example to search from the end or in parallel. Choosing between the two is a design decision. Make it on purpose and write it down.
Too Weak, Too Strong
Getting a specification wrong usually means it is either too weak or too strong.
| Failure | What it looks like | Consequence |
|---|---|---|
| Postcondition too weak | "Returns a common divisor of `a` and `b`" | Wrong algorithms (always return 1) count as correct |
| Postcondition too strong | "Returns the first match, found in at most 3 comparisons" | No algorithm can satisfy it in general |
| Precondition too weak | `find_max` with no "non-empty" requirement | The algorithm must handle `[]`, but `xs[0]` crashes |
| Precondition too strong | GCD requiring `a > b > 0` | Correct but less useful; callers must reorder or special-case inputs |
| Mixing in the "how" | "Repeatedly takes remainders until zero" | Rules out other valid algorithms; it describes an algorithm, not a problem |
A weak precondition and a strong postcondition give the caller the most, and they make the algorithm harder to write. A strong precondition and a weak postcondition make the algorithm easy to write and leave the caller with less. A good specification asks for exactly what the callers need and assumes exactly what they can guarantee.
A Template to Reuse
Before you describe any algorithm in plain language, pseudocode or code, fill in this template:
Problem: <short name>
Inputs: <name : domain>, ...
Output: <name : domain>
Precondition: <facts the caller guarantees about the inputs>
Postcondition: <relationship between output and original inputs>
Edge cases: <empty input, zero, duplicates, not found, ties>Writing out the edge cases forces you to settle them in the specification. Otherwise they get settled by accident, by whatever your first implementation happens to do.
Exercise
Write a full specification (inputs, output, precondition, postcondition) for find_max. Then name a lazy function that would pass if you left out the clause "m is an element of xs".
Show answer
Inputs: xs, a list of values comparable with >=. Output: m, a value. Precondition: xs is non-empty. Postcondition: m is an element of xs, and m >= x for every x in xs. Without the membership clause, a function that always returns float('inf') (for numeric lists) satisfies "m >= x for every x", so it would wrongly count as correct.
Exercise
A colleague specifies integer division as "Inputs: integers n and d. Output: integers q and r. Postcondition: n == q * d + r." Identify one missing precondition and one way the postcondition is too weak, and fix both.
Show answer
Missing precondition: d != 0 (and, if you want the usual definition, n >= 0 and d > 0). The postcondition is too weak because q = 0, r = n always satisfies n == q*d + r. Add the clause 0 <= r < d (for d > 0), which makes q and r unique.
Exercise
Is "returns the final value of a after the loop ends" an acceptable postcondition for GCD? Explain.
Show answer
No. It refers to the algorithm's internal variable, not to the problem, so it describes an implementation rather than a specification. It also makes every program that returns a trivially "correct", since there is no independent standard to check against. The postcondition must relate the output to the original inputs, for example: g > 0, g divides both inputs, and no larger integer divides both.