cs-045 — The Median That Lies
| Field | Value |
|---|---|
| id | cs-045 |
| difficulty | Beginner |
| topics | debugging, statistics |
| lecture | lecture-12 |
| estimated time | 5-minute attempt + 10-minute discussion |
| prerequisites | none |
| objective | state inputs, outputs, and assumptions, then solve a small instance by hand |
| solution | held by the instructor; discussed after the attempt |
Problem
A median function returns wrong values for even-length lists. Localise, fix, and add regression tests so it never regresses.
Your deliverable is the minimal failing input, the ranked hypotheses, the located mechanism, the minimal fix, and a regression test. If the problem is ambiguous anywhere, state the assumption you are making and carry on — a stated assumption is part of a good answer.
Examples
- Input: [1, 3, 2] -> 2 ok (odd length, middle element); [1, 2, 3, 4] -> buggy returns 3, correct is 2.5
- Output: bug: takes the element at index len//2 even for even lengths; fix: average the two middle elements
Solve for the worked instance first. Then ask what would change if one number, name, or condition were replaced by something stranger.
What to notice
- Even length has TWO middle elements; the buggy code quietly picks the left one.
- A bug is a claim about your mental model; the failing input is the experiment.
- The fix should be smaller than the explanation of the bug.
Discussion starter
After the solution is revealed, the class spends five minutes on this prompt: "Write the one-line commit message that explains the mechanism, not the symptom."
Constraints and assumptions
- Difficulty: Beginner (no prior experience assumed).
- Topics: debugging, statistics.
- Classroom-scale inputs unless the problem says otherwise.
- Time-box: about five minutes for a first attempt; partial answers with clear reasoning are worth more than silent struggling.
- Optional stretch (not required): describe an alternative approach and say when it beats the obvious one.
Hints and extension
- First nudge: identify the pattern the worked instance uses before computing anything.
- If stuck after three minutes, write the input/output line you expect and trace the smallest example by hand.
- After the reveal, attempt the extension below before the next lecture.
- Extension challenge: Write the regression test that would have caught the defect earliest.