Text, Collection Contracts and Source Corrections
Original teaching and optional independent application for the complete unit-3 source study. Retain and read the assigned chapters; use this companion to resolve the specific errors and version boundaries explained below.
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
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.
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.
Compare the complete changed-record 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.
Complete executable laboratory
Copy the entire source into collection_contracts.py and run python collection_contracts.py with Python 3.12 or later. The recorded execution used Python 3.12.14 and passed eleven unittest methods, including independent search/count oracles and temporary-package subprocess comparisons. Tests cover the stated finite examples and contracts, not every interpreter or possible program. Source SHA256: 0ebd6abbc7f8f4649cb522677b3a46efaa907763b2a1dc72d7b26e5b28b68ab4. No packages, network access, learner account or personal files are needed.
Primary references and retained assigned chapters
- Retained complete beginner source, chapters 4, 6, 8, 9, 11 and 20
- Python 3.12 built-in types: text, mappings and views
- Python 3.12 Unicode normalization
- Python 3.12 string constants
- Python 3.12 import system: relative imports and main metadata
- Python 3.12 built-in functions
Lawfare Academy is part of the Knowledge Institute, a Lawfare Group free education initiative. All practice is optional.