The Lawfare Academy

Lawfare Group → Knowledge Institute → Lawfare Academy

← CS 101 — Programming Foundations with Python

Weeks 6–8

Functions, decomposition and collection design

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.

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 reasoning The 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.

Extended teaching and laboratory

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).

Step-by-step reasoning 1. IDs 1 and 2 are different events despite equal amounts. The retry of ID 1 is the same event, leaving Ada at 1000 cents.

  1. 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.
  1. 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.
  1. 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.

Apply the idea

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).

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.

Read the worked reasoning

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.

Check understanding

When is replacing a list with a set incorrect?

  1. When repeated equal records represent distinct observations
    Feedback

    A set erases multiplicity, which is meaningful in transaction data.

  2. Whenever lookup speed matters
    Feedback

    Lookup needs do not justify changing the meaning of the data.

  3. Only when the list is empty
    Feedback

    The defect can occur in any nonempty list with meaningful duplicates.

Further reading

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.

My learning →