cs-044 — The Aliasing Trap
| Field | Value |
|---|---|
| id | cs-044 |
| difficulty | Advanced |
| topics | lists, aliasing, debugging |
| lecture | lecture-11 |
| estimated time | 5-minute attempt + 10-minute discussion |
| prerequisites | functions, dictionaries, and earlier algorithmic patterns |
| objective | design the algorithm, verify it on edges, and argue correctness or trade-offs |
| solution | held by the instructor; discussed after the attempt |
Problem
A matrix is built as [[0]3]2 and rows mutate together. Explain why, then build it correctly. Aliasing as the deepest beginner trap.
Your deliverable is the diagnosis of why the two rows mutate together, the corrected construction, and a written prediction of the same trap for a matrix built with append in a loop. 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: grid = [[0]3]2; grid[0][0] = 9
- Output: both rows become [9, 0, 0] - the two rows are one object; fix: [[0]*3 for _ in range(2)]
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
- Print id(grid[0]) and id(grid[1]) - identical ids convict the alias immediately.
- Slices are half-open: they make boundaries explicit instead of hidden in loop conditions.
- Aliasing is the difference between copying a list and copying a name.
Discussion starter
After the solution is revealed, the class spends five minutes on this prompt: "When is the extra memory of slicing worth it, and when would you insist on in-place?"
Constraints and assumptions
- Difficulty: Advanced (functions, dictionaries, and algorithmic reasoning assumed).
- Topics: lists, aliasing, debugging.
- Classroom-scale inputs unless the problem says otherwise.
- Time-box: about five minutes for a defensible plan; a complete solution may take longer and that is expected - state where you would resume.
- 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: Convert your in-place solution to a copying one and compare the trade-offs.