cs-047 — The Swap That Wasn't
| Field | Value |
|---|---|
| id | cs-047 |
| difficulty | Intermediate |
| topics | debugging, tuples, references |
| lecture | lecture-12 |
| estimated time | 5-minute attempt + 10-minute discussion |
| prerequisites | loops, lists, and tracing from lectures 1-6 |
| objective | choose the technique, trace it faithfully, and defend the boundary behaviour |
| solution | held by the instructor; discussed after the attempt |
Problem
An attempted in-place swap of list elements fails silently for one ordering. Trace it, find why, and enumerate every ordering in a test.
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: swap a[i], a[j] via tuple assignment inside a loop that also reassigns indices
- Output: swap works syntactically; the defect is the index update order - enumerate all orderings in tests
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
- a[i], a[j] = a[j], a[i] never fails silently - but a[i] = a[j] then a[j] = a[i] does; find which is in the code.
- 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: Intermediate (loops and lists assumed).
- Topics: debugging, tuples, references.
- Classroom-scale inputs unless the problem says otherwise.
- Time-box: about five minutes for the plan and trace; finishing the details is a bonus, defending the method is the target.
- 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.