Project: production-style debugging and refactoring
Refactor an order-sensitive grouping routine without changing its external contract. Reproduce the original issue with nested or duplicate data, define ownership, then add regression tests before replacing repeated scans with explicit lookup state.
Save privately stores your edited code, notes and current section. Runs and public checks are not saved as verified scores.
Before you start
Learners ready to reason about Python internals, resource boundaries and the listed prerequisites.
Explore the connected curriculum and preparation map
Lesson content version 2026-10-27. Suggested core budget: 40 minutes; optional deep dive: 25 more minutes. These are reading/practice estimates, not a timed test.
Suggested preparation and repair routes
- Logging and configuration boundaries
- Profile time and memory with evidence
- Fixtures, mocks and stronger tests
If an example or checkpoint feels unclear, revisit the relevant foundation and return. These links do not lock the lesson or claim you passed a prerequisite.
Actual runtime and local-lab boundaries
Browser Python 3.13: fresh isolated worker, 4-second execution, 16 KiB output, 256 MiB Python heap; no outbound network, host processes, interactive input or package installation.
Supported snippets run in the browser; temporary files and SQLite data disappear after each run. Models are labelled conceptual, not traces of your edited source. Full operating-system/framework/cloud labs need separate approval.
Public checks, revealed answers and project self-checks are learning feedback, not verified mastery or problem acceptance. Saving code does not execute it.
- Translate requirements into contracts
- Implement and test a complete small slice
- Explain production gaps and next increments
Project brief and review
Refactor an order-sensitive grouping routine without changing its external contract. Reproduce the original issue with nested or duplicate data, define ownership, then add regression tests before replacing repeated scans with explicit lookup state. Reading time does not include your independent implementation time.
Requirements
- Preserve first-occurrence order.
- Reject or document unsupported record shapes.
- Do not mutate caller-owned inputs.
- Explain algorithmic cost and retain regression tests.
Acceptance checklist
These self-checks are page-local, not saved or automatically judged.
Further increments
- Profile representative workloads before and after the change.
- Add streaming input and a cardinality limit rather than silently allowing unbounded groups.
Build this as a multi-file project: Order-sensitive debugging and refactoring
A pure regression/refactoring project, not measured production profiling. Exact list input; each row is a two-item list/tuple with exact string key and exact integer amount. Empty strings, case, whitespace, zero and negative values are supported; bool and nested mutable values are rejected. The known-bug baseline is intentionally not a solution. The lesson's single-file browser runner does not import these files.
- Preview and download the starter. In Standalone Playground, sign in and choose Import JSON as a new local project. Importing replaces local editor files only after its existing unsaved-edit confirmation; export your work first.
- Run and inspect baseline.py's known-bug reproduction: repeated list scans followed by sorting change first-key order. Add a regression that fails that behavior before editing grouping.py. Do not repair the baseline fixture; it preserves evidence of the original bug.
- Implement group(records) in grouping.py with private dictionary state, first-occurrence order and no input mutation or returned mutable aliases. Validate every row including late duplicates. Return a fresh list of (key,total) tuples, retaining zero and negative totals. Expected work O(n), space O(k), assuming bounded hash/string/integer costs.
- Implement bounded_group(records, max_groups) in transfer.py without changing the exact list/row contract. An exact nonnegative limit counts distinct keys, not rows. Existing keys may accumulate at capacity; new keys beyond it raise ValueError, never a partial result. Streaming input and measured performance remain separately qualified extensions.
- Save snapshot explicitly, then Run current files to execute
main.py's 10 public standard-library tests. The suite stops at the first failure; the untouched starter raises a realNotImplementedError. Inspect the named failing case, edit and rerun. Add an original test and explain why it would catch a tempting wrong approach. - Stop an active program before changing its baseline. Export current project JSON to keep your exact files; import the original starter as a separate local project to reset, with the same edit-loss confirmation. A saved version can be restored explicitly. Record your saved artifact and limitations separately if private project self-review is enabled.
Public tests are visible and editable, not exhaustive grading or proof that you worked without the reference. No completion, reading milestone or judge acceptance is awarded. Run needs the independently enabled approved Python Playground runtime; if unavailable, source editing/export remains available without a fallback. Frameworks, cloud services, live APIs and persistent database sessions remain unsupported. For local work, download all previewed source files into the same empty folder and run python main.py from that folder in your own Python 3.11+ environment. Downloads do not install Python or provide offline server execution.
References are excluded by default. Including them changes only the new download, never your current lesson or saved project.
Project brief and boundaries
A debugging project begins with a reproducible mismatch between a stated contract and observed behavior, not with a preferred rewrite.
Understand first
A faster grouping routine can still break callers by sorting keys, dropping duplicates or changing input ownership.
Words you will see
- Regression
- A previously fixed behavior becoming wrong again.
- Minimal reproducer
- A small input that still exposes the defect.
- Observable contract
- The values, order, errors and ownership callers can detect.
Freeze the behavior before choosing containers
For the guided project, records contain a string key and an exact integer amount; negative and zero amounts are supported. Output is a new list of immutable key-total pairs in each key's first-occurrence order. Repeated keys aggregate even when separated by another key. Unsupported nested keys and malformed rows must be rejected explicitly by the new validated increments.
The sample contrasts first-occurrence order with alphabetical order. Both contain the same keys but expose different sequences. Capture a regression with a nonalphabetical first key so a sorted implementation cannot accidentally pass. Also write empty, duplicate, zero and ownership cases before changing the implementation.
Separate repair from unrelated decisions
A missing total, a mutation leak and a slow repeated scan may share code but need different evidence. Reproduce the actual symptom first, trace where data changes, then make one explainable repair. Do not lowercase keys or discard zero totals merely because it seems cleaner. Those are contract changes requiring their own acceptance cases.
The deterministic browser tasks isolate these data rules. The independent project must reconstruct the reproducer, preserve the original requirements and rerun regressions before profiling. A first-seen dictionary avoids sorting and uses expected linear work for n records under bounded hashing/equality assumptions. Sorting k keys adds O(k log k) comparison work and changes the required order, so it is not an interchangeable optimization.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
records = [("worker", 1)Put a nonalphabetical key first so order matters.
first_seen = list(dict.fromkeys(key for key, _ in records))Keep the first occurrence of each key.
sorted_keys = sorted(first_seen)Construct a different, alphabetic contract.
print(sorted_keys)Observe that equal membership does not imply equal sequence.
Refactor an order-sensitive grouping routine without changing its external contract. Reproduce the original issue with nested or duplicate data, define ownership, then add regression tests before replacing repeated scans with explicit lookup state.
Conceptual debugging evidence chain, not a profiler trace
Conceptual reasoning steps for the original example, not a live trace of your edited Python.
- ReproduceUse a small nonalphabetical duplicate fixture.
- SpecifyAssert value, type, first occurrence and caller ownership.
- RepairChange lookup state; rerun regressions before measuring growth.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Change the first occurrence.
Try: Move the api record to the beginning.
Both displayed orders now start api; this weaker fixture would not expose accidental sorting.
Keep a zero-valued group.
Try: Change both worker amounts to 0.
The first_seen keys remain worker then api; values do not remove identities.
Before you move on
For keys z, a, z, should the combined z group appear before a even if z totals zero?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
Yes. First occurrence determines order and zero groups are retained. Neither alphabetical sorting nor filtering zero totals was requested.
Design a testable slice
A refactor changes the internal route while keeping supported external behavior. Private lookup state can replace repeated scans without borrowing caller containers.
Understand first
Appending directly to an input row may make totals look right while corrupting data reused elsewhere.
Words you will see
- Aliasing
- Two references reaching the same mutable object.
- Accumulator
- Private state holding a result during calculation.
- Copy depth
- How far ownership separation extends into nested objects.
Reproduce the ownership defect
The sample reads a caller-owned nested list, accumulates integers in a private dictionary and builds new list rows. Changing the returned total afterward leaves the source unchanged. Copying only the outer records list would retain aliases to its inner rows; assigning result[0][1] could still alter the caller's first record.
The guided validated reducer returns tuples instead of mutable rows. Strings and exact integers are immutable, so the returned list is the only mutable supported output container. Validate each two-item list or tuple before adding, reject bool amounts, and do not sort. On failure discard the private accumulator and leave every input row untouched.
Sequence tests before measurement
Start with one row and a duplicate separated by another key. Save a deep copy of the input before success and error calls. Compare afterward, then mutate the returned outer list and compare again. This catches both eager mutation and a returned alias. A shallow equality check before calling the function proves nothing about what the function changes later.
For n records and k groups, ordinary dictionary accumulation uses expected O(n) lookup operations and O(k) state plus output. A repeated linear search can grow toward O(nk). Those claims assume bounded-size keys, equality and integer arithmetic. Deep copying arbitrary objects is not automatically safer; it may duplicate resources or invoke custom behavior. Restrict shapes explicitly rather than advertising universal copying.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
records = [["api", 2], ["api", 3]]Supply nested mutable caller rows.
totals[key] = totals.get(key, 0) + valueAccumulate into a private mapping.
report = [[key, value] for key, value in totals.items()]Allocate a fresh mutable row per group.
report[0][1] = 99Probe result mutation without changing input rows.
Write down the public behaviour before changing data structures. A dict preserves insertion order while supporting expected constant-time key lookup, but hashing/equality and key size remain assumptions. Keep the algorithm pure so a regression is easy to reproduce.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Expose shallow aliasing.
Try: Replace the report comprehension with report = records[:].
Changing report[0][1] now changes the first caller row, reproducing the ownership bug.
Retain a zero total.
Try: Change the second amount to -2 and remove the report mutation.
The report includes api with total zero; it is not filtered out.
Before you move on
Would report = records[:] satisfy a promise that changing report[0][1] leaves records unchanged?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
No. The outer list is new but its inner rows are shared. Construct fresh rows for the supported shape, or return immutable tuples built from validated immutable fields.
Aggregate without mutating input
The original grouping reference uses a dictionary as lookup state and emits its items in first-key order. Its simplicity depends on a supported-input contract.
Understand first
Reading the exact baseline prevents a repair from quietly changing order, mutation behavior or error assumptions.
Words you will see
- Hashable key
- A key with stable hashing and equality suitable for dictionary lookup.
- Insertion order
- The order keys were first added, retained when their values change.
- Baseline
- The behavior against which a proposed change is compared.
Follow the preserved original program
group creates totals privately, unpacks each record into key and value, reads an old total or zero, adds the value and writes the new total. The second api record updates an existing key and does not move it after worker. list(totals.items()) returns a new outer list whose pairs are tuples.
The fixture snapshots simple input with deepcopy, asserts empty input and prints api 5 then worker 1. Its final post-call equality assertion checks the supplied input remained unchanged. The earlier pre-call equality alone would not have established ownership. Exact strings and integers make this fixture easy to reason about without custom hashing or addition.
Preserve strengths and identify unsupported shapes
The original loop does not validate all possible records. An unhashable list key raises TypeError, an incorrectly sized row fails unpacking, and custom additive values may have surprising ownership behavior. Keep the original example unchanged, then add a separately documented restricted validator in the guided increment. Do not describe that new restriction as something the original already guarantees.
For n records and k distinct keys, expected lookup work is O(n) and retained grouping state is O(k) under bounded hashing, equality and addition. Large strings and large integers affect costs. This browser-local pure function is not a completed deployment. Independent project work retains regression tests, then measures representative workloads and defines release, rollback and monitoring separately if used in a real service.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
totals = {}Own a fresh accumulator for this call.
for key, value in records:Unpack this fixture's two-item records.
totals[key] = totals.get(key, 0) + valueUpdate the total without moving an existing key.
assert records == beforeThe final occurrence checks input preservation after the call.
The output contract keeps first-key order and aggregates duplicate keys. The post-call assertion verifies input ownership; a complexity discussion must still state hash-table assumptions.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Make the repeated total zero.
Try: Change the last api value from 3 to -2.
The output retains ('api', 0) before worker.
Try the unsupported key boundary.
Try: Change one api key to ['api'].
The baseline raises TypeError rather than normalizing or silently dropping the record.
Before you move on
If the input keys are worker, api, worker, what order does list(totals.items()) retain?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
worker then api. Updating worker's amount does not remove and reinsert its key, so its original position remains.
Freeze the external contract before refactoring
The grouping routine accepts key-value records, accumulates repeated keys, preserves each key's first occurrence, and must not mutate caller-owned inputs. Write down supported key and value shapes before changing containers. The supplied records api 2, worker 1, and api 3 produce api 5 followed by worker 1. This is an ordering-sensitive contract: an alphabetically sorted output or a set of totals can contain equivalent amounts while still breaking callers' required sequence.
The reference dictionary implementation relies on hashable keys and additive values, with expected constant-time dictionary access under ordinary assumptions. It does not reject every unsupported nested shape with a carefully designed error. A nested mutable value can also interact with custom addition behavior. Decide whether to reject such inputs or support them under explicit ownership semantics rather than claiming that a short tuple-unpacking loop is a general-purpose aggregation engine.
Use numbered debugging increments with a preserved baseline
1. Reproduce the original wrong output, unexpected mutation, or slow path using a minimal failing fixture. 2. Capture the public expectations as regression assertions. 3. Trace repeated scans and object ownership. 4. Replace lookup state with a dictionary while keeping normalization and formatting unchanged. 5. Rerun regressions before measuring growth. Keep bug repair and unrelated cleanup separate so a reviewer can identify which change explains the observed behavioral difference.
A repeated search through an expanding result list can require quadratic lookup work. Dictionary accumulation changes that to expected O(n) operations for n records and O(k) retained groups for k keys, assuming bounded-cost hashing, equality, and addition. Large strings or custom keys affect these assumptions. First-key insertion order supplies the required output order without a separate sort, but an explicitly sorted downstream format would add a different cost and contract.
Create regression, ownership and measurement acceptance
Test empty input, one key, repeated keys separated by others, zero or negative values if supported, and keys with equal-looking representations but different semantics. Check the returned item sequence for first-occurrence order. Make a deep copy of representative nested input before calling the function and compare afterward on success and failure. The reference performs a post-call comparison for its simple records; that is useful narrow evidence, not proof for every custom mutable object.
Include unsupported record shapes and document whether they raise a domain validation error or are outside the function's contract. A new streaming input test should expose assumptions about indexing or repeated traversal. Benchmark representative cardinalities and key distributions only after correctness agrees with the baseline. Separate input creation from processing if the claimed metric excludes it, record environment details, and avoid declaring a universal speedup from one small fixture or a profiler's ranking alone.
Manage failure, release scope and independent effort
Keep aggregation local until success so a later invalid record cannot expose a normal partial report. If output is written incrementally, introduce explicit incomplete-output and cleanup rules rather than assuming the pure function's failure behavior carries over. Add a cardinality limit or spill strategy for unbounded distinct keys. A stream removes input retention only; it does not remove the dictionary or the final list of grouped pairs allocated by the reference.
Plan a reproduction session, an implementation-and-test session, and a later independent extension review rather than treating the reference as a finished assessment. Save evidence of the original failure and explain why each new test would catch its return. This executable slice does not establish monitoring, rollout, rollback, real process pools, or deployed reliability. Production-style reasoning means identifying those missing boundaries accurately, not adding operational vocabulary to a pure grouping fixture.
Transfer question: The refactored routine is correct for small inputs but memory rises with distinct keys. How would you extend it without hiding the new limit?
State that exact grouping retains O(k) groups and that streaming alone cannot remove that requirement. Add an explicit maximum cardinality with an actionable failure, or move to partitioned or database-backed aggregation. If preserving global first-occurrence order, store each key's first sequence position and order the final groups by that position; ordinary external key sorting would otherwise change the contract. Test equivalence against the small pure routine, then high cardinality, storage failure, and cleanup. Keep the original ownership and order regressions, and document the new storage dependency rather than advertising the extension as free constant-memory grouping.
Can you explain it?
Try from memory. Feedback stays on this page and does not award judged progress.
Build before opening the reference
Preserve first-occurrence order. Reject or document unsupported record shapes. Do not mutate caller-owned inputs. Explain algorithmic cost and retain regression tests. Demonstrate the acceptance cases and document any unsupported requirement.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Guided practice and transfer
These are public local learning checks, not certified scores. Edited code is saved only with Save work and place. Run results are not stored as certified scores. Export useful unsaved work before leaving.
A short function primer before you begin
def names a reusable rule. The input names in parentheses are parameters. Indent its body; replace the starter's pass placeholder. The body runs when called, not when defined.
return hands a value back and ends that call. print only displays a value. The public assert checks call your function with fresh fixtures; a false condition raises AssertionError with its message.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Increment 1: freeze first-occurrence order
Extract the ordering regression before rewriting the full reducer.
The contract
- records is an exact list of two-item lists/tuples. Keys are exact strings, including empty strings and case differences; amounts are exact integers, including zero and negatives, but not bool. Invalid shapes/types raise ValueError. Preserve every caller-owned row on success and failure.
- Return a fresh list of each key once in first-occurrence order. Do not sort, trim, lowercase or inspect totals to remove a key.
- Validate all records even when their key has already appeared. Pure browser-local values only; no I/O or global retained state.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Inspect 6 public checks
Transparent local learning checks, not exhaustive or tamper-proof grading.
- Nonalphabetical duplicates
from copy import deepcopy arguments = ([['z', 1], ['a', 2], ['z', 3]],) before = deepcopy(arguments) try: result = first_keys(*arguments) except ValueError: result = ("ValueError",) assert arguments == before, "Caller input changed" expected = ['z', 'a'] assert type(result) is type(expected), "Wrong result type" assert result == expected, "Wrong result value" def check_types(actual, target): assert type(actual) is type(target), "Wrong nested result type" if type(target) in (list, tuple): for item, wanted in zip(actual, target): check_types(item, wanted) elif type(target) is dict: for key in target: check_types(actual[key], target[key]) check_types(result, expected) if type(result) is list: result.append(("ownership-probe", 0)) elif type(result) is dict: for value in result.values(): if type(value) is list: value.append(("ownership-probe", 0)) assert arguments == before, "Caller input changed through result alias" - Empty records
from copy import deepcopy arguments = ([],) before = deepcopy(arguments) try: result = first_keys(*arguments) except ValueError: result = ("ValueError",) assert arguments == before, "Caller input changed" expected = [] assert type(result) is type(expected), "Wrong result type" assert result == expected, "Wrong result value" def check_types(actual, target): assert type(actual) is type(target), "Wrong nested result type" if type(target) in (list, tuple): for item, wanted in zip(actual, target): check_types(item, wanted) elif type(target) is dict: for key in target: check_types(actual[key], target[key]) check_types(result, expected) if type(result) is list: result.append(("ownership-probe", 0)) elif type(result) is dict: for value in result.values(): if type(value) is list: value.append(("ownership-probe", 0)) assert arguments == before, "Caller input changed through result alias" - Empty key, case and zero
from copy import deepcopy arguments = ([('', 0), ('A', -1), ('a', 1), ('', 2)],) before = deepcopy(arguments) try: result = first_keys(*arguments) except ValueError: result = ("ValueError",) assert arguments == before, "Caller input changed" expected = ['', 'A', 'a'] assert type(result) is type(expected), "Wrong result type" assert result == expected, "Wrong result value" def check_types(actual, target): assert type(actual) is type(target), "Wrong nested result type" if type(target) in (list, tuple): for item, wanted in zip(actual, target): check_types(item, wanted) elif type(target) is dict: for key in target: check_types(actual[key], target[key]) check_types(result, expected) if type(result) is list: result.append(("ownership-probe", 0)) elif type(result) is dict: for value in result.values(): if type(value) is list: value.append(("ownership-probe", 0)) assert arguments == before, "Caller input changed through result alias" - Late duplicate still validates
from copy import deepcopy arguments = ([['x', 1], ['x', True]],) before = deepcopy(arguments) try: result = first_keys(*arguments) except ValueError: result = ("ValueError",) assert arguments == before, "Caller input changed" expected = ("ValueError",) assert type(result) is type(expected), "Wrong result type" assert result == expected, "Wrong result value" def check_types(actual, target): assert type(actual) is type(target), "Wrong nested result type" if type(target) in (list, tuple): for item, wanted in zip(actual, target): check_types(item, wanted) elif type(target) is dict: for key in target: check_types(actual[key], target[key]) check_types(result, expected) - Nested unsupported key
from copy import deepcopy arguments = ([[['x'], 1]],) before = deepcopy(arguments) try: result = first_keys(*arguments) except ValueError: result = ("ValueError",) assert arguments == before, "Caller input changed" expected = ("ValueError",) assert type(result) is type(expected), "Wrong result type" assert result == expected, "Wrong result value" def check_types(actual, target): assert type(actual) is type(target), "Wrong nested result type" if type(target) in (list, tuple): for item, wanted in zip(actual, target): check_types(item, wanted) elif type(target) is dict: for key in target: check_types(actual[key], target[key]) check_types(result, expected) - Malformed row
from copy import deepcopy arguments = ([['x', 1, 2]],) before = deepcopy(arguments) try: result = first_keys(*arguments) except ValueError: result = ("ValueError",) assert arguments == before, "Caller input changed" expected = ("ValueError",) assert type(result) is type(expected), "Wrong result type" assert result == expected, "Wrong result value" def check_types(actual, target): assert type(actual) is type(target), "Wrong nested result type" if type(target) in (list, tuple): for item, wanted in zip(actual, target): check_types(item, wanted) elif type(target) is dict: for key in target: check_types(actual[key], target[key]) check_types(result, expected)
Why is a set-only return inadequate?
The set supports expected constant-time membership while the list records the required sequence. For n rows and k keys, expected work is O(n) and retained state O(k), assuming bounded field costs. The output contract is an ordered list. Set membership discards the sequence callers rely on, and returning a set also changes type.
Increment 2: aggregate without ownership leaks
Replace repeated scans with private lookup state while keeping order, signed amounts and validation.
The contract
- records is an exact list of two-item lists/tuples. Keys are exact strings, including empty strings and case differences; amounts are exact integers, including zero and negatives, but not bool. Invalid shapes/types raise ValueError. Preserve every caller-owned row on success and failure.
- Return a fresh list of (key, total) tuples in first-occurrence order. Aggregate all repeated keys and retain zero totals.
- All mutable output containers are private; no caller mutation or returned row alias. No I/O, sorting, key normalization or external state.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Inspect 6 public checks
Transparent local learning checks, not exhaustive or tamper-proof grading.
- Separated duplicates retain order
from copy import deepcopy arguments = ([['z', 2], ['a', 1], ['z', 3]],) before = deepcopy(arguments) try: result = validated_group(*arguments) except ValueError: result = ("ValueError",) assert arguments == before, "Caller input changed" expected = [('z', 5), ('a', 1)] assert type(result) is type(expected), "Wrong result type" assert result == expected, "Wrong result value" def check_types(actual, target): assert type(actual) is type(target), "Wrong nested result type" if type(target) in (list, tuple): for item, wanted in zip(actual, target): check_types(item, wanted) elif type(target) is dict: for key in target: check_types(actual[key], target[key]) check_types(result, expected) if type(result) is list: result.append(("ownership-probe", 0)) elif type(result) is dict: for value in result.values(): if type(value) is list: value.append(("ownership-probe", 0)) assert arguments == before, "Caller input changed through result alias" - Empty report
from copy import deepcopy arguments = ([],) before = deepcopy(arguments) try: result = validated_group(*arguments) except ValueError: result = ("ValueError",) assert arguments == before, "Caller input changed" expected = [] assert type(result) is type(expected), "Wrong result type" assert result == expected, "Wrong result value" def check_types(actual, target): assert type(actual) is type(target), "Wrong nested result type" if type(target) in (list, tuple): for item, wanted in zip(actual, target): check_types(item, wanted) elif type(target) is dict: for key in target: check_types(actual[key], target[key]) check_types(result, expected) if type(result) is list: result.append(("ownership-probe", 0)) elif type(result) is dict: for value in result.values(): if type(value) is list: value.append(("ownership-probe", 0)) assert arguments == before, "Caller input changed through result alias" - Zero and signed totals
from copy import deepcopy arguments = ([['a', 2], ['a', -2], ['', -1]],) before = deepcopy(arguments) try: result = validated_group(*arguments) except ValueError: result = ("ValueError",) assert arguments == before, "Caller input changed" expected = [('a', 0), ('', -1)] assert type(result) is type(expected), "Wrong result type" assert result == expected, "Wrong result value" def check_types(actual, target): assert type(actual) is type(target), "Wrong nested result type" if type(target) in (list, tuple): for item, wanted in zip(actual, target): check_types(item, wanted) elif type(target) is dict: for key in target: check_types(actual[key], target[key]) check_types(result, expected) if type(result) is list: result.append(("ownership-probe", 0)) elif type(result) is dict: for value in result.values(): if type(value) is list: value.append(("ownership-probe", 0)) assert arguments == before, "Caller input changed through result alias" - Case stays significant
from copy import deepcopy arguments = ([('A', 1), ('a', 2), ('A', 0)],) before = deepcopy(arguments) try: result = validated_group(*arguments) except ValueError: result = ("ValueError",) assert arguments == before, "Caller input changed" expected = [('A', 1), ('a', 2)] assert type(result) is type(expected), "Wrong result type" assert result == expected, "Wrong result value" def check_types(actual, target): assert type(actual) is type(target), "Wrong nested result type" if type(target) in (list, tuple): for item, wanted in zip(actual, target): check_types(item, wanted) elif type(target) is dict: for key in target: check_types(actual[key], target[key]) check_types(result, expected) if type(result) is list: result.append(("ownership-probe", 0)) elif type(result) is dict: for value in result.values(): if type(value) is list: value.append(("ownership-probe", 0)) assert arguments == before, "Caller input changed through result alias" - Late bad amount
from copy import deepcopy arguments = ([['ok', 2], ['bad', False]],) before = deepcopy(arguments) try: result = validated_group(*arguments) except ValueError: result = ("ValueError",) assert arguments == before, "Caller input changed" expected = ("ValueError",) assert type(result) is type(expected), "Wrong result type" assert result == expected, "Wrong result value" def check_types(actual, target): assert type(actual) is type(target), "Wrong nested result type" if type(target) in (list, tuple): for item, wanted in zip(actual, target): check_types(item, wanted) elif type(target) is dict: for key in target: check_types(actual[key], target[key]) check_types(result, expected) - Unsupported nested key
from copy import deepcopy arguments = ([['ok', 1], [['bad'], 2]],) before = deepcopy(arguments) try: result = validated_group(*arguments) except ValueError: result = ("ValueError",) assert arguments == before, "Caller input changed" expected = ("ValueError",) assert type(result) is type(expected), "Wrong result type" assert result == expected, "Wrong result value" def check_types(actual, target): assert type(actual) is type(target), "Wrong nested result type" if type(target) in (list, tuple): for item, wanted in zip(actual, target): check_types(item, wanted) elif type(target) is dict: for key in target: check_types(actual[key], target[key]) check_types(result, expected)
Why test signed amounts rather than only positive values?
The supported fields are immutable, and new tuple pairs separate output from nested input rows. Expected work is O(n) with O(k) grouping state and output under bounded hashing/equality/addition costs. An accidental filter for positive totals would pass many simple fixtures but incorrectly drop zero and negative groups supported by this contract.
Transfer: limit distinct groups honestly
Add a cardinality boundary without changing duplicate handling or returning truncated success.
The contract
- records is an exact list of two-item lists/tuples. Keys are exact strings, including empty strings and case differences; amounts are exact integers, including zero and negatives, but not bool. Invalid shapes/types raise ValueError. Preserve every caller-owned row on success and failure.
- max_groups is an exact nonnegative integer. Return the same new tuple-list report as the reducer, but raise ValueError before admitting a new key beyond the limit. At capacity, existing keys may still accumulate.
- An empty report at limit zero succeeds. Never return a normal partial result or mutate input on a late failure. Browser data task only; no files or spill storage.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Inspect 6 public checks
Transparent local learning checks, not exhaustive or tamper-proof grading.
- Repeated keys at capacity
from copy import deepcopy arguments = ([['z', 1], ['a', 2], ['z', -1]], 2) before = deepcopy(arguments) try: result = bounded_group(*arguments) except ValueError: result = ("ValueError",) assert arguments == before, "Caller input changed" expected = [('z', 0), ('a', 2)] assert type(result) is type(expected), "Wrong result type" assert result == expected, "Wrong result value" def check_types(actual, target): assert type(actual) is type(target), "Wrong nested result type" if type(target) in (list, tuple): for item, wanted in zip(actual, target): check_types(item, wanted) elif type(target) is dict: for key in target: check_types(actual[key], target[key]) check_types(result, expected) if type(result) is list: result.append(("ownership-probe", 0)) elif type(result) is dict: for value in result.values(): if type(value) is list: value.append(("ownership-probe", 0)) assert arguments == before, "Caller input changed through result alias" - Zero capacity and empty
from copy import deepcopy arguments = ([], 0) before = deepcopy(arguments) try: result = bounded_group(*arguments) except ValueError: result = ("ValueError",) assert arguments == before, "Caller input changed" expected = [] assert type(result) is type(expected), "Wrong result type" assert result == expected, "Wrong result value" def check_types(actual, target): assert type(actual) is type(target), "Wrong nested result type" if type(target) in (list, tuple): for item, wanted in zip(actual, target): check_types(item, wanted) elif type(target) is dict: for key in target: check_types(actual[key], target[key]) check_types(result, expected) if type(result) is list: result.append(("ownership-probe", 0)) elif type(result) is dict: for value in result.values(): if type(value) is list: value.append(("ownership-probe", 0)) assert arguments == before, "Caller input changed through result alias" - New key at zero capacity
from copy import deepcopy arguments = ([['a', 1]], 0) before = deepcopy(arguments) try: result = bounded_group(*arguments) except ValueError: result = ("ValueError",) assert arguments == before, "Caller input changed" expected = ("ValueError",) assert type(result) is type(expected), "Wrong result type" assert result == expected, "Wrong result value" def check_types(actual, target): assert type(actual) is type(target), "Wrong nested result type" if type(target) in (list, tuple): for item, wanted in zip(actual, target): check_types(item, wanted) elif type(target) is dict: for key in target: check_types(actual[key], target[key]) check_types(result, expected) - Late new key exceeds limit
from copy import deepcopy arguments = ([['a', 1], ['a', 2], ['b', 3]], 1) before = deepcopy(arguments) try: result = bounded_group(*arguments) except ValueError: result = ("ValueError",) assert arguments == before, "Caller input changed" expected = ("ValueError",) assert type(result) is type(expected), "Wrong result type" assert result == expected, "Wrong result value" def check_types(actual, target): assert type(actual) is type(target), "Wrong nested result type" if type(target) in (list, tuple): for item, wanted in zip(actual, target): check_types(item, wanted) elif type(target) is dict: for key in target: check_types(actual[key], target[key]) check_types(result, expected) - Bool limit rejected
from copy import deepcopy arguments = ([], True) before = deepcopy(arguments) try: result = bounded_group(*arguments) except ValueError: result = ("ValueError",) assert arguments == before, "Caller input changed" expected = ("ValueError",) assert type(result) is type(expected), "Wrong result type" assert result == expected, "Wrong result value" def check_types(actual, target): assert type(actual) is type(target), "Wrong nested result type" if type(target) in (list, tuple): for item, wanted in zip(actual, target): check_types(item, wanted) elif type(target) is dict: for key in target: check_types(actual[key], target[key]) check_types(result, expected) - Duplicate record still validates
from copy import deepcopy arguments = ([['a', 1], ['a', True]], 1) before = deepcopy(arguments) try: result = bounded_group(*arguments) except ValueError: result = ("ValueError",) assert arguments == before, "Caller input changed" expected = ("ValueError",) assert type(result) is type(expected), "Wrong result type" assert result == expected, "Wrong result value" def check_types(actual, target): assert type(actual) is type(target), "Wrong nested result type" if type(target) in (list, tuple): for item, wanted in zip(actual, target): check_types(item, wanted) elif type(target) is dict: for key in target: check_types(actual[key], target[key]) check_types(result, expected)
Does accepting a stream remove the need for the group limit?
The check occurs only for a new identity, so input length is not mistaken for cardinality. For n rows and g allowed groups, expected work is O(n), and retained state plus output O(min(n, g)) under bounded field costs. No. Exact totals still retain a state entry for each distinct key; a stream only avoids retaining all input rows at once.
Core route complete.
If you can explain the checkpoint and attempt the practice, move on. Come back for the deep dive when you want the why behind the how.
Save your core reading milestoneProduction hardening is separate
A cardinality limit bounds distinct groups, not input length. Streaming removes one source of retention but does not eliminate grouping state.
Understand first
A million repeated records may form one group, while a million distinct records require a million exact totals unless the storage strategy changes.
Words you will see
- Cardinality
- The number of distinct keys.
- Streaming
- Consuming input incrementally rather than first retaining all records.
- Spill strategy
- Moving retained work to another storage layer when memory is insufficient.
Change the requirement explicitly
The transfer adds max_groups as an exact nonnegative integer. A new key at the limit raises ValueError; another record for an existing key is allowed. At zero, empty input succeeds and any new group fails. Keep first-occurrence order, duplicate aggregation and caller preservation unchanged.
The sample demonstrates the condition before inserting a new key. Check membership before updating so repeated keys remain legal at capacity. Never return the first few groups as an ordinary complete report after exceeding the limit. The exception must discard private candidate state; input rows remain untouched on late failure.
Choose the next resource boundary
A hard limit is simple and predictable but rejects legitimate high-cardinality work. Partitioning or database-backed aggregation can extend capacity while adding storage failure and cleanup cases. Preserving global first-occurrence order then needs each key's earliest sequence position; sorting keys in external storage would change the contract.
For n records and at most g groups, the bounded reducer retains O(g) state and expected O(n) lookup work under bounded field costs. A stream does not make that constant memory for unlimited distinct keys. Implement the transfer independently, then build local representative memory and failure tests if adopting external storage. The finite browser policy proves no disk cleanup, crash recovery or deployed resource ceiling.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
keys = ["worker", "api", "worker"]Supply three records but only two distinct keys.
seen = set()Track group identities without producing output order here.
if key not in seen and len(seen) >= limit:Reject only an additional identity at capacity.
seen.add(key)Repeated worker does not increase cardinality.
One correct fixture is not an operational release. Add instrumentation, realistic size limits, deployment/rollback planning and review of error handling. Separate bug repair from unrelated formatting or architectural changes so the behavioural difference is auditable.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Exceed cardinality.
Try: Append "db" to keys.
The sample raises when db would become the third distinct key.
Allow only empty input.
Try: Set keys to [] and limit to 0.
The empty case prints 0; a zero group limit need not reject an empty report.
Before you move on
At max_groups=1, do two rows for api exceed the limit? What about api followed by worker?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
Two api rows form one group and are allowed. A later worker introduces a second distinct key and raises ValueError without a partial successful report.
Review and transfer
Correctness comparison and performance measurement answer different questions. Establish equivalent behavior before interpreting timing.
Understand first
A rewrite that drops groups can look faster. Operation counts can explain growth without making unreliable wall-clock claims in a browser.
Words you will see
- Differential check
- Comparing two implementations on the same supported input.
- Workload
- The size and distribution of inputs used in a measurement.
- Operation model
- A simplified count of work, not measured elapsed time.
Explain the performance hypothesis
The sample counts comparisons when finding all-new keys by scanning an expanding list. Four unique keys need zero plus one plus two plus three comparisons. That count excludes input construction and arithmetic and is not elapsed time. Repeated keys near the front can behave differently, so distinct-key distribution belongs in the workload description.
After a real reproducer and ownership regressions pass, compare the old supported implementation with the new one on fresh fixtures. Include empty, repeated and nonalphabetical cases. If the baseline contains a known defect, compare against the intended contract for that case rather than demanding identical wrong output. Keep unsupported shapes documented instead of treating incidental exceptions as universal guarantees.
Keep release evidence bounded
For a local profiling lab, create representative sizes outside the measured region if construction is excluded, record the interpreter and environment, repeat measurements and inspect allocation as well as runtime. Do not infer universal speedup from four records or a profiler ranking. Input key lengths, cardinality, hash behavior and integer size all affect cost.
The browser experiment below is deterministic arithmetic evidence only. Independent project work includes its own reproduction, code repair, regressions and a changed requirement before any release decision. A real deployment additionally needs observable failures, size limits and a rollback plan. Passing public checks or opening a reference is not proof of mastery, operational reliability or a completed deployment.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
unique_keys = ["a", "b", "c", "d"]Choose an all-distinct fixture required by this model.
seen = []Start with no earlier keys to scan.
comparisons += len(seen)Count a full failed scan before each insertion.
seen.append(key)Increase the next search length by one.
After implementation, explain the boundary cases and change one requirement without rewriting unrelated behaviour. Profile representative workloads before and after the change. Add streaming input and a cardinality limit rather than silently allowing unbounded groups. Keep a record of what you tested; a viewed reference is not proof you independently completed the project.
Run your edited Python in the browser, or download it. Ctrl/Cmd + Enter runs. One example runs at a time; each run starts fresh. Save work and place stores a private copy of edited code. Run results remain local learning feedback. No third-party execution service receives your code.
Preparing the editor controls. Run and editing become available when this page is interactive.
Browser Python limits
Python 3.13 with browser-compatible standard-library modules and prebundled SQLite, a 4-second execution limit, 16 KiB output and a 256 MiB Python heap cap. First loading can take up to 45 seconds. Total browser memory is browser-governed. No network, learner package installation, interactive input, host files or system processes. SQLite databases and temporary files disappear after each run. Platform-specific examples may report unsupported modules; download those for a suitable local environment.
Change one thing; explain the difference.
Add one distinct key.
Try: Append "e" to unique_keys.
The modeled comparison count becomes 10.
Use a one-key workload.
Try: Set unique_keys to ["only"].
It prints 0 because the first insertion has no earlier keys to scan.
Before you move on
If the all-distinct fixture grows from four to five keys, how many comparisons does this model add?
Try explaining it in your own words. Running code is useful, but the explanation above gives you enough to reason it through first.
Read a worked answer
Four more, making ten total. The fifth new key scans the four already-seen keys; this says nothing about a particular elapsed time.
Make the explanation your own.
Use Save work and place to store notes with your code. Unsaved edits stay in this course tab; export before leaving. Reading milestones remain separate.
Take a versioned study copy
Export this lesson's original theory, textual model explanations, worked examples, public exercise checks and local-runtime boundaries for reading/review. This is separate from exporting your private workspace: no learner code, notes, identity, saved place or results are included. Offline server/browser execution is not provided.
Worked examples and explained concept checkpoints remain included. Reference answers for independent work are excluded unless you explicitly select them. A downloaded answer is not an earned pass.
Make this a milestone.
Save a self-reported core reading milestone and confidence. Confidence 1-3 schedules a review when none is already set; higher confidence does not create a new review. This is not a code execution pass or proof of mastery. Deep-dive reading is optional and is not tracked separately yet.