CS 101 — Programming Foundations with Python · Weeks 6–8
Functions, decomposition and collection design
Full teaching sequence and cumulative subject work
Work parameter binding, return values, scope, string indexing, sequence traversal, mutation and dictionary accumulation. Complete exercises from each chapter, including at least one that fails because a list is aliased. Explain the failure before correcting it. Then study the original assigned documentation as a language reference and complete the worked and transfer problems.
Collections, identity and aliasing
A collection design encodes identity. Equal field values do not prove that two transactions are the same transaction. Deduplicating by an identifier can be valid only if the identifier contract and conflict rule are explicit. A second issue is aliasing: two names may point to the same mutable list. Copying an outer dictionary does not necessarily copy the lists inside it.
State the expected operation before choosing a list, set or mapping. A list preserves order and multiplicity. A set retains distinct values. A mapping associates a key with its current value; storing several events per customer requires a collection as that value. Mutation tests should check both returned values and whether input data changed unexpectedly.
Worked problem
Transactions are (id 1, Ada, 500), (id 2, Ada, 500), and a retry of (id 1, Ada, 500). Compute customer totals under an event-ID deduplication contract. Then process (id 1, Ada, 700).
Trace the complete reasoning
IDs 1 and 2 are different events despite equal amounts. The retry of ID 1 is the same event, leaving Ada at 1000 cents.
Keep a mapping from event ID to the accepted payload. A seen-ID set alone can detect repetition but cannot distinguish an identical retry from a conflicting reuse.
The changed ID 1 payload is a conflict. Reject or quarantine it under a documented correction procedure; silently ignoring it conceals a discrepancy, while adding it double counts.
If producing grouped lists, use a new list per key. Sharing one list among customers would allow one customer’s append to alter another customer’s history.
Independent transfer problem
A correction event ID 3 reverses event 1 for −500 and replacement event ID 4 adds 700. Show Ada’s net and explain why preserving events aids reconciliation.
Compare the transfer solution
The accepted ledger is +500, +500, −500, +700, totaling 1200 cents. Event IDs 3 and 4 document correction rather than rewriting history. A repeated delivery of either correction ID must also be idempotent. Reconciliation can now trace the original amount, its reversal, and the replacement; a final dictionary total alone cannot explain the change.
Learning objectives
- Explain and trace the mechanisms in functions, decomposition and collection design.
- Apply the method to the worked example and changed-condition exercise.
- Identify assumptions, failure cases and the evidence needed to justify a result.
Study the mechanism
Functions give a name and contract to a coherent operation. A good boundary reduces the number of facts a caller must remember. A calculation function should not also ask for keyboard input, overwrite a file and send a message. Those effects make it difficult to test independently and difficult to reuse. Return structured data to a coordinating function that decides how to display or persist it.
Choose collections according to meaning. A list preserves an ordered sequence and allows duplicates. A set represents membership without multiplicity. A dictionary associates keys with values; replacing an existing key does not create an additional occurrence. Consequently, converting transaction records to a set may erase valid repeated transactions, while aggregating with a dictionary can intentionally combine amounts by customer. The choice is part of the data model.
Mutation changes an existing object. Two names can refer to the same list, so a change through one name can affect code using the other. A shallow copy protects the outer container but still shares nested objects. Avoid mutable default arguments because defaults are created when the function is defined, not anew for every call. When a function promises not to modify its input, test that promise. Type hints describe expectations but do not enforce them automatically at runtime. Document output ordering, missing keys and malformed records; these are observable behaviors that downstream users may depend on.
Worked example
def by_customer(records):
totals = {}
for customer, cents in records:
totals[customer] = totals.get(customer, 0) + cents
return totals
rows = [("Ada", 500), ("Ben", 700), ("Ada", 500)]
assert by_customer(rows) == {"Ada": 1000, "Ben": 700}
assert len(rows) == 3The first Ada record inserts a key with 500. Ben creates a different key. The second Ada record retrieves 500 and replaces its value with 1000. Both Ada transactions contribute, even though they have identical fields. The input list is only read. Turning rows into a set first would collapse the two equal Ada tuples and produce a wrong total. That loss is a model error, not a dictionary defect.
Check your understanding
When is replacing a list with a set incorrect?
- When repeated equal records represent distinct observations
- Whenever lookup speed matters
- Only when the list is empty
Answer and reasoning for every option
Correct: When repeated equal records represent distinct observations A set erases multiplicity, which is meaningful in transaction data.
Reconsider: Whenever lookup speed matters Lookup needs do not justify changing the meaning of the data.
Reconsider: Only when the list is empty The defect can occur in any nonempty list with meaningful duplicates.
Transfer laboratory: Aliasing and a misleading copy
A dictionary contains a list of work orders. A second dictionary is made with original.copy(). Appending through the second dictionary changes the original list. Explain why and choose a suitable boundary.
Work through the full solution
dict.copy creates a new outer mapping but shares references to nested mutable values. The lists are still the same object. If isolation is required, create independent nested lists or use a justified deep copy; if shared state is intended, document it. A deep copy is not a substitute for a sound ownership model, especially with resources that cannot be meaningfully copied. Test both outer-key changes and nested-list mutation.
Evidence of understanding
Distinguish new container identity from shared nested objects and demonstrate the chosen ownership policy.
Complete on-site teaching readings
These are full attributed source sections, not previews. Read them alongside the original Academy explanation and code.
- 5. Data Structures · Python Software Foundation and Python documentation contributors
- 9. Classes · Python Software Foundation and Python documentation contributors
- 6. Modules · Python Software Foundation and Python documentation contributors
Open the complete practice sequence and cumulative assessment →