Names, Exact Money and Conservation

Original teaching and a complete Python laboratory for unit 1. Move from statement-by-statement prediction to a precise parser, signed rounding and an allocation proof. All transaction amounts are synthetic. Practice is optional; compare your reasoning after attempting it.

From an expression to a reproducible program

Start with a small experiment before the invoice calculation. Open an installed Python 3 interpreter and enter 6250 * 3. Its interactive prompt displays 18750. In a saved file named estimate_demo.py, the same expression alone produces no displayed output: the interpreter evaluates the expression, but the script has no instruction to display it. Write print(6250 * 3), save, and run the file with the Python command available on your system, for example python3 estimate_demo.py. Do not type the >>> prompt into the file. Record the actual interpreter version with python3 --version, or the equivalent command you use. The numerical examples here do not require one particular editor.

Now execute these four assignments in order: rate_cents = 6250; hours = 3; total_cents = rate_cents * hours; hours = 4. After the third assignment the names refer to 6250, 3 and 18750. The fourth changes hours to 4, while total_cents still refers to 18750. Re-evaluating rate_cents * hours would yield 25000, but merely changing a name does not re-run an earlier expression. A trace must record values after each statement, rather than drawing an arrow from total to a permanently active formula. An expression produces a value; assignment binds its result to a name.

Types help explain another failure. Text returned by input is a string, so '6250' * 3 repeats four-character text three times. It does not yield a monetary total. Converting '6250' to an integer is appropriate only after deciding that the text denotes cents. The text '62.50' denotes dollars under a different contract. Trying int('62.50') raises ValueError; converting through float and then int can silently truncate or introduce a representation error. A parser should implement the accepted notation and units directly.

A boundary contract that can be tested

For the accompanying laboratory, a dollar input consists of an optional + or - sign, one through twelve ASCII whole-number digits, and an optional decimal point followed by one or two digits. Ordinary spaces may surround it. The complete incoming string may contain at most 32 characters. Examples are '19.95', '+19.9', '19' and '-0.05'. A missing whole-number part, exponent notation, currency symbols, commas, underscores, tabs, nonfinite values and more than two fractional digits are rejected. These are deliberate application rules; Python's numerical constructors accept a wider language. Another product could make different choices, but its choices need their own tests.

Parsing '19.9' first identifies sign, whole digits 19 and fractional digits 9. Pad the fraction on the right to 90 hundredths; 100 * 19 + 90 gives 1990 cents. Parsing '-0.05' gives magnitude 5 and then applies the negative sign, yielding -5. Do not strip the decimal point and interpret the remaining digits without accounting for their positions: that would turn '19.9' into 199 cents. Validate before adding anything to a running total. Converting malformed text to zero would fabricate a legitimate transaction.

Display is a different transformation. For -5 cents, take the absolute magnitude, divide it into whole dollars and a remainder, pad the remainder to two digits, then add the sign: -$0.05. Applying floor division directly to a negative amount gives a different decomposition. For Python integers, -7 // 4 is -2 and -7 % 4 is 1, so (-2)*4 + 1 reconstructs -7. In contrast, int(-7 / 4) is -1 because conversion truncates toward zero. Neither operation is a general instruction to round to the nearest integer.

Derive the rounding rule before implementing it

Suppose an exact result is the signed rational number N/D cents with positive integer D. Divide abs(N) by D to obtain quotient q and remainder r. The magnitude lies q + r/D cents from zero. If 2r < D, q is closer; if 2r > D, q+1 is closer. At equality our chosen rule takes the value farther from zero. Restore the original sign after this decision. This proves the rule implemented by round_ratio, including negative inputs. It also shows why adding 50 and flooring a signed numerator divided by 100 is not a symmetric extension of the earlier nonnegative formula.

For a five-cent charge discounted by 50%, N=250 and D=100. Quotient 2 and remainder 50 yield 3 cents under the tie rule. For an independently calculated five-cent credit, N=-250 gives -3 cents. The shortcut (-250+50)//100 instead yields -2, violating the stated symmetry. For a refund of a recorded invoice, first decide whether to reverse its recorded payable amount or calculate a new discounted credit. Arithmetic cannot choose the refund policy.

Decimal arithmetic also has a contract. Decimal('0.1') starts with the exact decimal tenth, while Decimal(0.1) converts the binary floating-point value already supplied. Decimal construction can preserve more digits than the current context precision; arithmetic results may then be rounded to that precision. Quantize supplies a target exponent and a rounding choice, while an Inexact trap can detect disallowed loss of nonzero digits. Decimal does not remove precision, input-validation or rounding-policy decisions. The laboratory tests those distinctions without using Decimal as the implementation of its integer-cent calculations.

Allocation is a conservation problem

To distribute 1000 cents equally over three positions, integer division gives a base share of 333 and one remaining cent. Give one extra cent to the earliest position under a declared stable ordering: [334,333,333]. The sum is exactly 1000 and the largest and smallest shares differ by at most one. For any nonnegative T and positive n, write T=nq+r with 0≤r<n. Giving q+1 to r positions and q to the others sums to r(q+1)+(n-r)q=nq+r=T. For a signed credit, allocate its magnitude and negate every share. This preserves both the total and reversal symmetry. Repeated allocations may favor early positions; rotating the order is a separate fairness policy that must be specified if required.

The original three-visit invoice pays 5387 cents after its invoice-level discount. Refunding each visit independently at 1796 cents would return 5388 cents across three refunds. Allocating the recorded payable amount instead gives [1796,1796,1795], whose sum reverses exactly the amount paid. Do not conceal the discrepancy by changing one result without recording the allocation rule.

Reading the assigned sources with a current interpreter

Read both complete beginner chapters, including their exercises, then the three complete Python tutorial chapters and the Decimal reference. Use the beginner chapters for explanation and the documentation for precise behavior. The older beginner edition illustrates PyScripter and contains a historical keyword list with exec. This course does not require that editor. In current Python 3, exec is a built-in function, while keyword.iskeyword('exec') is false; query keyword.kwlist on your own interpreter instead of treating the old list as current. Avoid naming a variable exec because that hides the built-in name. The Decimal reference also distinguishes Decimal's truncating // from integer floor division; choose the numeric type before transferring an arithmetic identity to code. The laboratory uses Python integers for the derived quotient/remainder algorithms.

Independent progression

First, trace rate_cents = 1250; hours = 2; saved = rate_cents * hours; hours = hours + 1. State both saved and the freshly evaluated product, and classify '1250' * 2. Next, predict parse_cents('+7.4'), format_cents(-7), and rejection of '7.400'. Then compute signed half-away-from-zero rounding for 249/100, 250/100 and -250/100 cents. Finally allocate two cents over five positions and allocate the recorded payable 5387 cents over three refundable visits. Supply a sum proof and a test that would expose independent per-item rounding. Attempt these before opening the companion's reasoning; no submission or quiz is required.

Compare the independent reasoning

After the first three assignments, saved is 2500 cents. The last assignment changes hours to 3, leaving saved at 2500; the newly evaluated product is 3750. The string operation produces the text 12501250, not 2500. If saved changes automatically in your trace, you are treating assignment as a live equation. If the string is added numerically, you have omitted conversion and its units.

The parser returns 740 cents for +7.4 because the one fractional digit denotes tenths of a dollar, or 40 cents. Displaying -7 cents yields -$0.07. Input 7.400 is rejected under this deliberately narrow syntax even though its mathematical value could be represented exactly; lexical policy and numeric equality answer different questions. To permit extra trailing zeroes, change the contract and tests explicitly.

249/100 gives 2 because the remainder 49 is below half the denominator. 250/100 gives 3 because the exact tie goes away from zero. -250/100 gives -3 by applying the same magnitude calculation and restoring the sign. A result of -2 identifies the invalid signed use of the old add-50 shortcut.

Two cents over five positions give [1,1,0,0,0]. Shares for 5387 cents over three visits are [1796,1796,1795], and refund shares are their negatives. A test must check both the total and a maximum spread of one, rather than accepting any three numbers with the correct sum. Three independent refunds of 1796 fail conservation by one cent. The stable earliest-position tie rule is part of this implementation; it is not a claim that the order is fair for every repeated allocation.

Inspect and run the complete implementation

Copy into representation_lab.py and run python representation_lab.py with Python 3.10 or newer, using python3 if that is your interpreter command. The nine test groups include a Fraction-based rounding oracle, exact input rejection, display round trips, signed allocation invariants, Decimal context distinctions and integer-contract failures. These tests validate the stated synthetic contract; they do not choose a real organization's billing or refund policy.

Source SHA-256: 9f2b640a915bff0ecfa66a8d9cb0ca80d55d32e0d409631a6128a27f3e717c7b

Complete Python source and executable tests

CS 101 — Programming Foundations with Python

A complete ledger pipeline with a falsifiable specification

Build a small program from a representation contract, not from a guessed output. The input is CSV with event_id, customer and cents. Equal amounts can be different transactions. An identical event-ID retry must not change the result, while a changed payload under the same ID is an error. Negative amounts represent valid credits. The output is a customer reconciliation and overall integer-cent total.

The reference implementation’s ledger and atomic_report functions separate parsing, accumulation and publication. Study them after completing the mapped beginner textbook chapters. Before running the code, calculate the result for events 1/Ada/500, 2/Ada/500, a retry of 1/Ada/500 and 3/Ada/−200. Then predict the outcome when an invalid last row is appended. The ordinary study path does not require submitting code, but proficiency requires being able to produce and explain a solution independently.

Complete assigned source studies

Produce the work

  1. Write preconditions and postconditions for ledger, including the identity-conflict rule.
  2. Trace the seen mapping and customer total after each row. Explain why a set of customer/amount pairs is wrong.
  3. Implement the pipeline independently, then compare output with the reference and the hand calculation.
  4. Create invalid-type, duplicate, conflicting-ID, empty-file and late-failure tests. Demonstrate that a failed run preserves the old published report.
Compare the full worked model

The two equal 500-cent events have different IDs and both contribute. The identical retry of event 1 contributes nothing further. The −200-cent credit produces an 800-cent total for Ada across three accepted event identities. A correct trace records seen[1]=(Ada,500) after the first event, adds seen[2] after the second, verifies rather than adds the retry, and then records the credit. Deduplicating by customer and amount would incorrectly collapse events 1 and 2.

The input boundary has several distinct duties. CSV syntax determines fields and quoting. The header contract determines which columns are accepted. Conversion determines whether cents is represented as an allowed integer string. Domain rules determine whether identity and customer fields are present and whether credits are permitted. An error should not be hidden by silently converting a malformed amount into zero. A changed payload under an accepted ID must be reported because a seen-ID set alone would conceal the conflict.

The function’s accumulator invariant is that totals contains exactly the sum of accepted unique events in the processed prefix, grouped by customer. The seen mapping contains the accepted payload for each identity. Initialization satisfies the empty-prefix case. Each new valid identity adds exactly one payload; an identical retry changes no state; a conflict raises rather than pretending the prefix defines a complete valid input. At successful termination, the invariant covers the whole file.

atomic_report validates before replacing the destination. The self-test writes a previous report, appends an invalid amount to the input and verifies that the old report remains unchanged. It then runs the valid input and verifies a new result. This demonstrates the stated failure boundary under the tested conditions. It is not a claim of complete durability after hardware failure or coordination among independent publishers. Those would need additional requirements.

The reference is intentionally small enough to trace. To extend it, specify whitespace, signed-number syntax, maximum field sizes, correction events and output encoding. Each extension should add a discriminating test and preserve the existing identity contract. A project that merely produces 800 once is incomplete as evidence; a project that explains the invariant, rejects the conflicting retry and preserves output on late failure demonstrates the mechanisms the course aims to teach.

Changed-case examination

The business now allows two independent writers to publish the same report path. Does atomic replacement alone decide whose result should win?

Compare the revised reasoning

No. Atomic replacement prevents a particular partial-file exposure but does not define ownership or version conflict policy. Add a run/version identifier and an explicit coordination mechanism. Test the policy with two writers; do not infer it from a successful single-process demonstration.

Self-evaluation

A complete response supplies the requested artifacts, shows the intermediate reasoning, uses source locators or independently calculated expected results, addresses the strongest relevant alternative, and revises the conclusion when the changed case alters its decisive premise. A correct selected answer alone does not substitute for producing this work.

Later integration study: corrected CSV boundaries

Test the parser boundary before trusting a reconciliation

An integration test can pass while the parser admits invalid documents. The earlier implementation_laboratories.py companion checked its column names inside the row loop. With input consisting only of wrong,header followed by a newline, the loop body never executes. It reports an empty valid ledger instead of rejecting the wrong header. This is a counterexample to the stated header contract, not a debate about the correct total of an empty transaction list. A genuine empty ledger has the required header and no data rows; an empty file has no header and is invalid under the corrected contract.

A second counterexample has header event_id,customer,cents,cents and data row 1,Ada,500,700. Converting a row to a dictionary collapses repeated column names, retaining the last amount. A set of dictionary keys cannot reveal that duplicate header. The earlier function reports 700 cents. Check reader.fieldnames before iteration: require exactly three entries and the set {event_id,customer,cents}. Together, length and set equality prove every required name occurs exactly once. Merely testing the set of raw header names also fails to reject the duplicate.

The corrected companion on Names, Exact Money and Conservation supplies the complete ledger and atomic_report functions and executable regressions. Column order may vary, but names may not repeat. It validates missing and extra cells separately, uses strict CSV parsing, and accepts integer cents only in the declared optional-minus, one-to-twelve ASCII-digit syntax. It does not use the dollar parser from unit 1: the column already denotes cents. Customer and event fields each contain 1–80 characters with no implicit stripping. Numeric normalization means 0500 and 500 denote the same amount under an identical event ID, while a changed customer or amount is a conflict. Quoted commas and newlines are parsed as field content rather than split manually.

The accumulator invariant begins only after the document's header is validated. After each accepted record, seen maps every unique event ID in the processed prefix to its normalized payload, and customer totals sum those unique payloads. An exact retry contributes nothing. A conflicting retry raises, so an incomplete prefix is not published as a complete reconciliation. Physical line numbers can differ from record numbers when quoted fields contain newlines. Diagnostics must not assume that one CSV record occupies one physical line.

Output has a separate failure boundary. Validate the entire input before creating a candidate file, write it in the destination's directory, close it, and replace the old name only after writing succeeds. Clean up an unused candidate in a finally block. Injecting a replacement failure tests a path that a late-input-failure test never reaches. Successful local replacement does not choose a winner between independent writers or establish recovery after power loss. Those require additional coordination and durability requirements.

Independent counterexample and changed condition

Required columns may appear in any order, exactly once. Predict the result for header cents,event_id,customer with rows 500,1,Ada; 500,2,Ada; 500,1,Ada; -200,3,Ada. Next append 501,1,Ada and predict whether a previously valid destination may change. Separately test a header-only input with duplicate cents columns. Finally inject an OSError immediately at replacement after a valid candidate is written. State which artifact should remain and which temporary artifact should disappear. Use the complete corrected companion for this exercise; retain the earlier implementation as the defect-comparison case.

Compare the parser and failure reasoning

The reordered document has three unique events and Ada totals 800 cents. The unchanged retry adds nothing. Appending event 1 with amount 501 conflicts with its accepted payload, so validation raises before the old report is touched. A duplicate-column header is invalid even with no data rows, because header validation precedes iteration. With a valid candidate but an injected replacement failure, the old destination remains and the candidate is removed by finally. A test that checks only parsing cannot establish candidate cleanup after a write or replace failure.

Save this separate source as ledger_boundaries.py and run it with Python 3.10 or newer. Nine regression groups exercise actual CSV parsing and local file replacement, including the two reproduced defects in the earlier companion.

CSV source SHA-256: 8538c251a15fcfd8891323948146de0be3ece001b9dc7455d757f9b0953f98c3

Complete corrected CSV companion and tests

Primary reference: DictReader fields and missing/extra cells · Primary reference: replacement semantics

Primary documentation and source orientation

The original beginner chapters and full assigned references remain in the course. Their PyScripter illustrations and keyword list are historical; use the current-interpreter orientation above. The complete Python performance-study assignment is retained above with its source link updated to the corrected companion. The earlier shared script remains available for defect comparison; use the corrected source for current Python assignments. The prose, records and source on this page are original Academy work. Whole-course and full-catalog acceptance remain separate from this unit expansion.