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.
  • Derive and implement a bounded search invariant and an overlap-count contract, including empty and invalid-bound cases.
  • Distinguish code-point equality, label normalization and opaque event identity using discriminating counterexamples.
  • Trace nested sharing, tuple hashability, numeric-key equality, collisions, live dictionary views and insertion order.
  • Separate interpreter syntax capability, package execution context and actual test-process failure signals.

Current study directions: the original Academy lessons, worked explanations and complete optional models on LawfareGroup.com provide the required conceptual preparation. Retained publisher/reference chapters and their historical reading directions are optional further study. Outside visits and assessments are optional. Independent subject review and observed learner testing remain pending.

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.

Read the Functions source with an executable contract

The complete assigned Functions chapter develops decomposition, parameter binding, calls, results and turtle-based composition. Retain those examples and their figures, and apply these corrections when running them. In section 4.5, final_amt_v3 declares compounded but uses the misspelled componded in its exponent. In a fresh environment the call raises NameError. Change that reference to compounded; changing the caller's variable name does not repair a misspelled name inside the function. The original names remain visible in the retained source so the discrepancy can be located exactly.

The same section assigns toInvest=float(input(...)). input returns text, then float converts it; after that complete assignment toInvest refers to a float, rather than the string described by the surrounding prose. Follow the nested calls from the inside out. For the synthetic input text '10000', input first supplies that string, float produces 10000.0, and assignment binds the caller's name to the float. When a function is called, its parameter name receives a reference to the supplied argument object. The parameter and caller names need not be spelled alike.

The source's arithmetic example illustrates a formula, not a complete money-record specification. Binary floating-point operations already incur rounding; printing two decimal places controls presentation and does not restore exact decimal information. The earlier exact-money laboratory remains the course's representation study. For the separate synthetic formula here, the new laboratory accepts nonnegative int or Fraction principal/rate values, excluding bool, a positive built-in integer number of periods per year, and a nonnegative built-in integer number of years. A rate of one tenth means 10 percent, not the integer ten. These are explicit mathematical experiment rules, not a prediction or recommendation about an investment.

Derive the recurrence before comparing renamed functions

Let p be the starting amount, r the annual fractional rate, n the periods per year and t the whole years. There are N=n*t updates and each update multiplies the current amount by f=1+r/n. The recurrence starts A0=p and uses A(k+1)=Ak*f. Induction gives Ak=p*f**k: it holds at zero, and multiplying the induction hypothesis by f gives the next case. At N updates the result is p*(1+r/n)**(n*t). The finite loop has the decreasing measure N-k. This argument establishes what the calculation means under the stated exact rational contract; a variable rename preserves it only if every reference and parameter binding is changed consistently.

For p=100, r=1/10, n=2 and t=1, the factor is 21/20. The trace is 100,105,441/4, so the final amount is exactly 110.25. With n=1, the factor is 11/10 and there is one update, giving 110. With t=0 there are zero updates and the result is the original 100. Changing a denominator or exponent while renaming parameters changes the calculation. The laboratory compares a multiplication loop with an independently expressed closed form over several exact records, including zero-time and zero-rate cases.

Distinguish a local name from the lifetime of its object

A function-local name is ordinarily unavailable through a global lookup after the call. That does not imply that every object used by the function is destroyed when it returns. A returned object can remain reachable through the caller's binding. The source's functions that return turtles already illustrate this distinction: a locally named turtle can be returned and used by the caller. Its object lifetime differs from the visibility of the function's ordinary local name.

The complete make_report example sets local_rows=list(rows) and returns {'orders':local_rows}. With source=['A'], make_report(source) gives a new outer list in report['orders']. Appending 'B' to source and 'C' to the report leaves source=['A','B'] and the report list=['A','C']. The list returned through the dictionary remains usable after make_report has returned. If another dictionary is created with report.copy(), it shares that report list: appending 'D' through the second dictionary also changes the first report's list. Distinguish the identity of the outer dictionaries from the identity of their nested value.

Now change the original input to [[1]]. list(rows) copies the outer list but retains a reference to the same inner list. Appending 2 to report['orders'][0] therefore changes the original input to [[1,2]]. This does not contradict the earlier flat-string example. The operation protected the outer list only; mutable nesting changed the ownership boundary that matters. State whether nested sharing is intended before choosing a deeper copy or an immutable representation.

Definition-time work, call-time work and retained state

Defining a function creates and binds a function object without running its body. Some expressions attached to the definition can still run then. A default argument is evaluated when the definition executes. If it produces a list, later calls using that default share the same list. The laboratory records 'default evaluated' once and 'body called' separately on each of two calls. Its remember function instead uses a None default and creates a new list inside for calls that omit an existing list. An explicitly supplied list is intentionally reused; a default policy should not conceal a different ownership policy for supplied arguments.

As a further lifetime example, make_counter creates count=0 and returns an inner increment function. The returned function uses nonlocal count to update the retained enclosing binding. Calling the outer function twice creates two separate enclosing bindings. Calls first(),first(),second(),first() return 1,2,1,3. Without nonlocal, an assignment to count inside increment would create a different local binding, and count+=1 would try to read that local before it was assigned. This explanation concerns lexical scope and retained references; it does not turn every local name into a global.

An effect and a returned value are also separate observations. A function that appends 'C' to a supplied list and reaches its end returns None. The list can change even though the returned value is None. The chapter's term void describes a function used for its effect; Python still supplies a return value. Inspect both the result and the permitted effects when testing a contract. The historical PyScripter debugger controls and __traceable__ setting in the source are editor-specific conveniences; understanding parameter and call traces does not require that editor or setting.

Independent changed record

Use the exact recurrence contract p=100, r=1/10, n=2, t=1 and derive every amount, then change n to 1 and t to 0 separately. Identify the failure when a function declares compounded but evaluates componded, and identify the resulting type of float('10000'). For make_report(rows), the full rule is local_rows=list(rows), followed by returning {'orders':local_rows}. With source=['A'], obtain report, append 'B' to source and 'C' to report['orders'], then make outer=report.copy() and append 'D' through outer['orders']. State every final list and which objects are shared. Repeat with source=[[1]] and append 2 through report['orders'][0]. Finally explain why two make_counter factories, each starting count=0 and returning a nonlocal increment function, produce 1,2,1,3 under first(),first(),second(),first(). Explain the contracts before comparing with the complete source; all practice is optional.

Reading corrections: text, collections and executable evidence

Use the complete assigned beginner chapters and the Data Structures, Classes and Modules references, together with the function-contract companion. The following orientation corrects identifiable source errors and supplies portable experiments. It preserves the original readings so their examples, arguments and exercises remain available. The laboratory below was executed with Python 3.12.14. A reference snapshot can describe syntax from a newer interpreter; a syntax error on an older interpreter is evidence about compatibility, rather than evidence that the underlying collection operation is impossible.

In Fruitful Functions section 6.2, incremental development makes a small change easier to investigate, but an error is not necessarily confined to the last line added. A new call can expose an older unchecked assumption. For example, a reciprocal-sum function can pass inputs [1,2] and still divide by zero when a later caller supplies [1,2,0]. Trace the failing operation and its preconditions rather than treating the location of the latest edit as a proof. The deliberately incomplete absolute_value example is an exercise in finding a bug, not an accidental error to erase. A divisibility helper using x%y also needs an explicit nonzero-divisor rule.

The chapter's small test helper reports a failed condition by printing a message. That is useful instructional feedback, but does not by itself make the process exit unsuccessfully. The new experiment runs a child process that prints 'Test FAILED' and exits zero, then a genuine failing unittest process that exits nonzero. A learner or automated runner must inspect the correct failure signal. Passing finite examples supports a claim within the tested cases; a loop invariant or domain argument supplies a different kind of justification.

The elementary distance calculation squares coordinate differences. It is appropriate for moderate values, but finite floating-point differences near 1e200 overflow when squared, while values near 1e-200 underflow to zero. math.hypot computes the corresponding finite or nonzero distances in these experiments. This is a boundary correction, not a promise that every distance between finite coordinates is representable: subtraction or the true final magnitude can itself exceed the floating-point range. The unit's earlier exact-arithmetic work remains relevant when a different numerical contract is needed. Functions section 4.4 also overstates max's argument rule: max(7) does not mean a one-value maximum, because the one-argument form expects an iterable. max() raises TypeError; max([]) raises ValueError unless an explicit default is supplied.

A bounded character search with a proof of its result

Define find_character(text,character,start,end) to search one Unicode code point in the half-open interval [start,end). Both text inputs must be strings, character must have length one, and start/end must be built-in integers excluding bool satisfying 0<=start<=end<=len(text). Return the first matching index or -1. These validation rules are deliberately narrower than str.find, which also supports substring needles, normalized slice-style bounds and an empty needle. Do not silently substitute one API's boundary rules for another's.

Initialize index=start. At the beginning of every iteration, no position from start up to index, excluding index, matches. This is true initially because that prefix is empty. If text[index] matches, the invariant establishes that the returned index is the first match in the requested interval. Otherwise advancing index by one extends the rejected prefix. The nonnegative remaining length end-index decreases at each unsuccessful step, so the loop terminates. At index=end every allowed position has been rejected and -1 is justified. Validation makes each indexed access safe, including an empty search interval.

For text='banana', character='a', start=2 and end=6, positions 2 and 4 contain 'n', while position 3 is the first allowed 'a'; the answer is 3. Changing start to 0 and character to 'b' gives 0. Test success with result>=0, not if result: index zero is falsey, while the failure marker -1 is truthy. The original custom search in Strings section 8.12 does not enforce this bounded contract. A negative starting index can produce a negative index for an actual match, and an end beyond the string can lead to IndexError. Reject bad bounds or explicitly implement the richer built-in semantics; an undocumented mixture is misleading.

For ordinary nonnegative step-one slices, an oversized stop is clamped, an oversized start gives an empty slice, and a start after the stop gives an empty slice. Thus len(text[start:end]) is not always end-start. Strings section 8.6's surrounding start/stop wording should be interpreted with these actual rules. Indexing outside the string raises, whereas slicing beyond it usually does not. Different operations have different boundary contracts.

Count occurrences by stating what counts as an occurrence

The Strings exercises expect overlapping matches: 'ana' starts at positions 1 and 3 in 'banana', so the requested count is two. Python's str.count uses non-overlapping matches and returns one. Neither result is a universal definition of count; the specification chooses the operation. For a nonempty needle of length m in text of length n, inspect every candidate start from zero through n-m, inclusive. Count the positions whose length-m slice equals the needle. When m>n, there are no candidates. The maintained total is the number of matching starts already inspected, and one new candidate either adds one or leaves it unchanged.

For 'aaaaaa' and 'aaa', the candidate starts 0,1,2,3 all match, giving four. A search-based independent oracle can instead call str.find repeatedly, resuming one position after each found start. Advancing by the needle length would suppress overlaps. This laboratory rejects an empty needle explicitly: accepting it would require a separate rule about the n+1 boundaries and careful termination. The two remove_letter exercise tests in Strings section 8.19 incorrectly use a single '=' inside the call. Change those comparisons to '=='; the original forms fail to parse before the function can be tested.

Unicode text requires a policy beyond ASCII examples

A Python string is a sequence of Unicode code points, so len('é') is one while len('e\u0301') is two. Those encodings can look alike to a reader, but are unequal before a chosen normalization. Code-point length is not a count of perceived characters, and normalization is not a general grapheme-segmentation algorithm. The example label policy composes to NFC, casefolds and composes to NFC again. It makes these two spellings of é match, and maps 'Straße' to 'strasse'. It deliberately preserves whitespace and punctuation. A different application may need a different policy; record the Unicode/interpreter version when exact text behavior is part of a reproducible result.

The source's assertion that all uppercase letters sort before lowercase letters is valid for the ASCII Latin examples, not for all Unicode. 'Å' compares after 'z' by code point. Ordinary string comparison does not implement a locale's dictionary ordering. Likewise string.punctuation and string.whitespace contain ASCII characters; they do not enumerate all Unicode punctuation or spacing. An em dash is absent from the former, and a nonbreaking space is absent from the latter even though str.isspace recognizes it and ordinary split separates on it. Deleting the hyphen in 'a-b' produces 'ab', merging rather than separating tokens. Before a word-frequency exercise, state whether punctuation is deleted, replaced by a separator, or retained, and which text equivalences the task permits.

Do not apply a convenient label policy automatically to event identities. If the contract defines opaque IDs by exact code-point sequences, the composed and decomposed strings remain two different IDs. Collapsing them can erase a legitimate event. Normalizing display labels and defining transactional identity are separate decisions. This connects the text examples to the unit's original repeated-event and conflict exercises.

Container identity, nested ownership and assignment order

Lists section 11.2 sets numbers=[17,123]; numbers[9-8] is therefore 123, not the printed 5. In section 11.9, equality of strings does not guarantee shared object identity. Python may intern some strings, but correct value comparison uses == rather than depending on that implementation choice. The laboratory intentionally does not assert that equal dynamically constructed strings must be either identical or distinct.

A tuple prevents replacement of its own entries, not mutation of an object referenced by an entry. For wrapped=([1],), wrapped[0].append(2) is allowed; hash(wrapped) raises TypeError because that contained list is unhashable. Tuple packing constructs the tuple on the right in pair=1,2; unpacking assigns its elements to targets on the left in first,second=pair. These directions clarify the reversed packing/unpacking wording in the Tuples chapter.

Repeated nested lists introduce a further ownership trap. In shared=[[0]*3]*2, both rows refer to the same inner list. After shared[0][0]=7 both displayed rows begin with 7. A comprehension [[0]*3 for _ in range(2)] creates each row separately, so changing one leaves the other alone. Draw two references to one object for the first case, and two objects for the second. An outer shallow copy does not change that underlying sharing. The earlier function-contract record tests the same distinction through a returned report dictionary.

Assignment evaluates its right-hand expressions before assigning targets, which explains x,y=y,x. It does not mean every group of targets changes atomically or without order. With i=0 and a=[0,0], i,a[i]=1,9 first sets i to 1, then assigns a[1], yielding [0,9]. Trace target evaluation left to right when targets depend on earlier assignments.

Hash keys, order and a corrected recurrence

Modern Python dictionaries preserve insertion order, guaranteed from Python 3.7; the beginner dictionary chapter's claim of unpredictable iteration order is historical. Updating an existing value keeps its position. Deleting a key and reinserting it moves it to the end. A keys view reflects subsequent changes, whereas list(mapping) captures a separate list of the keys at that time. Mutating dictionary size during iteration is a different issue and should not be used as an informal filtering strategy.

Keys require hashability, not merely an immutable outer container. A tuple containing a list is the counterexample above. A hash value is also not an identity: distinct CollisionKey('A') and CollisionKey('B') deliberately have the same hash in the laboratory and still occupy two entries because they compare unequal. Conversely 1,True and 1.0 compare equal and address one dictionary entry. If an identifier domain requires only strings or excludes bool, enforce that boundary before insertion. Expected constant-time hash lookup depends on implementation and hashing/equality assumptions; it is not a universal worst-case guarantee, especially with deliberate collisions or expensive key comparisons.

In Dictionaries section 20.2, eng2esp['dog'] refers to the wrong variable spelling and raises NameError in the shown isolated context. eng2sp['dog'] instead demonstrates the intended missing-key KeyError. Section 20.5's memoization prose also disagrees with its own code: the displayed Fibonacci cache uses F0=0 and F1=1, not a zero case equal to one. For n>=0 define F(n+2)=F(n+1)+Fn. An iterative implementation starts left=0,right=1 and updates left,right=right,left+right n times. At step k, the invariant is left=Fk,right=F(k+1), so the returned left is Fn. Its n-k termination measure and constant number of retained integer objects do not imply constant bit-space or constant-cost arithmetic as n grows.

The independent test oracle counts tilings of n-1 cells with one- and two-cell tiles for n>=1. If there are d double tiles, the total number of tiles is n-1-d; choosing the d double positions gives binomial(n-1-d,d). Sum over d=0 through floor((n-1)/2), and handle F0 separately. This derives expected values without repeating the iterative recurrence in the test. Both give F100=354224848179261915075. The recursive source remains useful for learning memoization, but Python's recursion-depth limit still applies; caching avoids repeated work, not unbounded call depth. Reject negative numbers and bool under this laboratory's explicit built-in integer contract.

Read reference syntax and package context precisely

The mapped Data Structures snapshot contains [*element for element in x], {*fruit for fruit in fruits} and {**i for i in all_values}; the Classes snapshot contains (*i for i in x). All four raise SyntaxError when compiled with the tested Python 3.12.14. The laboratory records capability by compiling source strings so the surrounding portable program still runs. Do not diagnose a learner's older interpreter from newer documentation alone. Portable flattening uses [value for group in groups for value in group], with corresponding set and generator forms; dictionary merging uses {key:value for group in groups for key,value in group.items()}, with the last equal key winning. These are explicit iteration orders rather than a guess that an unpacking operator works in every syntactic position.

The Modules snapshot's final statement that main modules must always use absolute imports is too broad. Directly executing a package member as a file usually lacks the package context needed for its relative import. Running python -m labpackage.runner from the package's parent gives the module that context, so from .helper import VALUE works. The complete temporary-package experiment below verifies both cases. It also imports the module twice in one process: its top-level 'loaded 7' prints once on the first normal import, while its main-guarded action does not run. Under -m both the top-level action and main-guarded action run. This distinguishes a guard from a promise of no import side effects. A module namespace is organization, not a security boundary; leading underscores and class name mangling do not grant access control. Example dir output varies with interpreter and platform and is not a portable exhaustive checklist.

Independent application before inspecting the solution

For the complete changed record, use text='banana' and search for the one-code-point character 'a' only in [2,5); return the first matching index or -1. Then search for 'b' in [0,6) and for 'z' in [0,6). State the rejected prefix at return and explain which numeric result is falsey. Count overlapping 'aaa' in 'aaaaaa' by inspecting every length-three slice, then compare the non-overlapping count. Reject an empty needle. Explain why accepting a start of -1 would require a different search contract.

Next take labels 'é' and 'e\u0301'. State their raw lengths and equality, then apply the stated NFC/casefold/NFC label policy. Under a separate exact-code-point ID contract, store each as its own event key with amounts 500 and 700. Show how applying the label policy to those keys would change the event count. Start data={'A':1,'B':2}, retain view=data.keys() and snapshot=list(data), update A to 3, delete A, then reinsert A=4. Give both final key sequences. For shared=[[0]*3]*2 and separate=[[0]*3 for _ in range(2)], change [0][0] to 7 and draw each final ownership relationship. Finally predict the outputs and success/failure of the supplied temporary package under direct-file, -m and twice-imported execution, before running the laboratory. All exercises remain optional; the complete solution explains why each result follows.

Complete package experiment contract: in a fresh temporary parent directory create labpackage/__init__.py empty, helper.py containing VALUE=7, and runner.py containing from .helper import VALUE, then print('loaded',VALUE), then if __name__=='__main__': print('main'). Run from that parent with the same Python interpreter: first python labpackage/runner.py, then python -m labpackage.runner, then a new child process executing import labpackage.runner twice. No earlier imports are present in either child. Predict each return status and output in order. The complete laboratory supplies this exact temporary package; no existing learner files need changing.

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.

Further independent function-contract record

Complete record contract: set A=p, N=n*t and f=1+r/n, then update A=A*f exactly N times using exact rational arithmetic. Principal p and annual fractional rate r are nonnegative int or Fraction values excluding bool; n is a positive built-in integer and t a nonnegative built-in integer. Zero updates return p. make_counter creates a separate count=0 binding per factory call and returns increment(), which uses nonlocal count, adds one and returns the updated count.

Use the exact recurrence contract p=100, r=1/10, n=2, t=1 and derive every amount, then change n to 1 and t to 0 separately. Identify the failure when a function declares compounded but evaluates componded, and identify the resulting type of float('10000'). For make_report(rows), the full rule is local_rows=list(rows), followed by returning {'orders':local_rows}. With source=['A'], obtain report, append 'B' to source and 'C' to report['orders'], then make outer=report.copy() and append 'D' through outer['orders']. State every final list and which objects are shared. Repeat with source=[[1]] and append 2 through report['orders'][0]. Finally explain why two make_counter factories, each starting count=0 and returning a nonlocal increment function, produce 1,2,1,3 under first(),first(),second(),first(). Explain the contracts before comparing with the complete source; all practice is optional.

Further independent text and collection record

For the complete changed record, use text='banana' and search for the one-code-point character 'a' only in [2,5); return the first matching index or -1. Then search for 'b' in [0,6) and for 'z' in [0,6). State the rejected prefix at return and explain which numeric result is falsey. Count overlapping 'aaa' in 'aaaaaa' by inspecting every length-three slice, then compare the non-overlapping count. Reject an empty needle. Explain why accepting a start of -1 would require a different search contract.

Next take labels 'é' and 'e\u0301'. State their raw lengths and equality, then apply the stated NFC/casefold/NFC label policy. Under a separate exact-code-point ID contract, store each as its own event key with amounts 500 and 700. Show how applying the label policy to those keys would change the event count. Start data={'A':1,'B':2}, retain view=data.keys() and snapshot=list(data), update A to 3, delete A, then reinsert A=4. Give both final key sequences. For shared=[[0]*3]*2 and separate=[[0]*3 for _ in range(2)], change [0][0] to 7 and draw each final ownership relationship. Finally predict the outputs and success/failure of the supplied temporary package under direct-file, -m and twice-imported execution, before running the laboratory. All exercises remain optional; the complete solution explains why each result follows.

Complete package experiment contract: in a fresh temporary parent directory create labpackage/__init__.py empty, helper.py containing VALUE=7, and runner.py containing from .helper import VALUE, then print('loaded',VALUE), then if __name__=='__main__': print('main'). Run from that parent with the same Python interpreter: first python labpackage/runner.py, then python -m labpackage.runner, then a new child process executing import labpackage.runner twice. No earlier imports are present in either child. Predict each return status and output in order. The complete laboratory supplies this exact temporary package; no existing learner files need changing.

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.

Further function-contract reasoning

For the exact two-period recurrence the amounts are 100,105,441/4. Changing to one annual period gives 110; changing to zero years gives 100. The misspelled componded is an unbound name in the isolated function and raises NameError; the minimal repair uses the declared compounded consistently. float('10000') returns a float with value10000.0. In the flat list record, source ends ['A','B']; report['orders'] and outer['orders'] both end ['A','C','D'] and refer to the same list, while the dictionaries themselves are distinct. In the nested record the copied outer lists differ, but both index0 values refer to the same inner list, so the original becomes [[1,2]]. Returned objects remain reachable after a function call even though its ordinary local name is not a global. Each counter factory creates a separate enclosing count binding; the first increment function retains and changes its own binding three times, while the second changes its own binding once. nonlocal selects that enclosing binding for assignment. These traces explain the observed results rather than attributing them to caller variable spelling or assuming every copy provides deep isolation.

Further text and collection reasoning

The bounded 'a' search rejects position2 ('n') and returns3. Searching 'b' returns0 with an empty rejected prefix; searching 'z' returns-1 after rejecting positions0 through5. Zero is falsey and -1 is truthy, so the correct success condition is index>=0. A start of -1 is rejected by this API; Python's own negative indexing does not give permission to return a negative position indistinguishable from the failure marker.

The length-three slices of 'aaaaaa' starting0,1,2,3 are all 'aaa', giving four overlapping matches. The non-overlapping count is two, using starts0 and3. Rejecting the empty needle keeps the candidate and termination contract explicit. If empty matches were allowed, define the n+1 boundaries separately rather than letting a loop repeatedly rediscover the same match.

The raw label lengths are1 and2 and the strings compare unequal. NFC/casefold/NFC maps both labels to 'é'. Under exact opaque event identities the original mapping has two entries with separate amounts500 and700. Transforming its keys to the common label key would merge them: a direct dictionary construction keeps only the later amount, not a valid two-event reconciliation. Normalization is appropriate only when that equivalence is part of the ID contract, not because the text looks alike.

Updating A preserves its original position; deleting it removes that position; reinserting it appends it. The live view therefore lists ['B','A'], while snapshot remains ['A','B']. In shared, both outer entries point to the same row [7,0,0]. In separate the first row is [7,0,0] and the second is [0,0,0], because the comprehension evaluates a new row construction each time. A new outer list by itself would not remove an already shared inner row.

With the provided helper VALUE=7 and runner containing from .helper import VALUE, a top-level print('loaded',VALUE) and a main-guarded print('main'), direct-file execution fails at the relative import without a known parent package. From the package parent, -m succeeds and prints 'loaded 7' then 'main'. Two normal imports in one child process print 'loaded 7' once and never 'main': ordinary import reuses the initialized module and __name__ is labpackage.runner. This experiment establishes the documented package-context distinction in the tested interpreter. It does not claim that arbitrary imports are pure or that every environment has the same search path.

Check understanding

When is replacing a list with a set incorrect?

  1. Whenever lookup speed matters
    Feedback

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

  2. Only when the list is empty
    Feedback

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

  3. When repeated equal records represent distinct observations
    Feedback

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

Further reading

Current study directions: the original Academy lessons, worked explanations and complete optional models on LawfareGroup.com provide the required conceptual preparation. Retained publisher/reference chapters and their historical reading directions are optional further study. Outside visits and assessments are optional. Independent subject review and observed learner testing remain pending.

Use the original worked investigations and optional changed-record models in this unit. Historical directions below are retained as source history and do not require publisher chapters.

My learning →