cs-055 — The Parameter Jungle
| Field | Value |
|---|---|
| id | cs-055 |
| difficulty | Intermediate |
| topics | functions, defaults, mutation |
| lecture | lecture-14 |
| 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
A function with a mutable default argument accumulates state across calls. Diagnose, fix, and generalise the lesson to API design.
Your deliverable is the function list with contracts, the composed driver, and one input per function that exercises its edge. 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: def add_tag(tag, tags=[]): called three times
- Output: the default list persists: calls accumulate; fix: None sentinel + fresh list
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
- Defaults are evaluated ONCE at definition. Print id(tags) across calls to watch it stay the same.
- A good function name is a miniature specification.
- Return values compose; printed output does not.
Discussion starter
After the solution is revealed, the class spends five minutes on this prompt: "Where would this decomposition crack if the input format changed?"
Constraints and assumptions
- Difficulty: Intermediate (loops and lists assumed).
- Topics: functions, defaults, mutation.
- 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: Split one function into two and defend the new contract boundary.