Build a study-session analyser
Combine validation, collections, functions and tests into one useful project.
Save privately stores your edited code, notes and current section. Runs and public checks are not saved as verified scores.
Before you start
Learners who can read small Python functions and want to apply the listed foundations.
Explore the connected curriculum and preparation map
Lesson content version 2026-10-27. Suggested core budget: 25 minutes; optional deep dive: 15 more minutes. These are reading/practice estimates, not a timed test.
Suggested preparation and repair routes
- Files, JSON and resource boundaries
- Tests that catch real mistakes
- Package and ship a tested command-line tool
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.
- Aggregate records without mutating inputs
- Validate before updating totals
- Test a complete small program
Project brief and review
Combine validation, collections, functions and tests into one useful project. Reading time does not include your independent implementation time.
Requirements
- Aggregate nonnegative integer study minutes per topic.
- Reject blank topics, booleans and negative minutes.
- Do not mutate caller-owned records.
Acceptance checklist
These self-checks are page-local, not saved or automatically judged.
Further increments
- Add separately tested JSON/CLI adapters.
- Add per-day summaries with an explicit timezone contract.
Build this as a multi-file project: Study analyser
A bounded standard-library study core, independent transfer and public tests, not a long-running service, database session or cloud environment. 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.
- Implement study_totals(records) in study.py: dictionary records, trimmed nonblank topics, exact nonnegative integer minutes (zero valid, bool invalid), case and first-occurrence order. Invalid fields/shapes raise ValueError. Do not mutate input or return a partial report.
- Implement event_counts(services) in transfer.py independently. Preserve exact string labels, including whitespace, case and empty strings, count every occurrence in first-occurrence order and leave input unchanged. Empty input returns an empty mapping.
- Add an original test and explain why it would catch a tempting wrong approach. Expected aggregation work is O(n) with O(k) groups under bounded field costs; a stream alone does not bound distinct-group memory.
- Save snapshot explicitly, then Run current files to execute
main.py's 15 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.
The brief
A project brief is a promise about inputs and outputs. Translate each sentence into an observable case before choosing the loop.
Understand first
Study records contain repeated sessions, not one row per topic. The analyser must combine sessions while preserving what the caller supplied.
Words you will see
- Contract
- The rules a caller can rely on.
- Normalization
- Converting equivalent spellings to one agreed form.
- Acceptance case
- A concrete input and expected outcome that checks a requirement.
Turn the brief into cases
A record supplies a topic string and exact integer minutes. Surrounding whitespace is removed from the topic; case remains significant. Zero is valid, negative minutes and booleans are not. A missing value is not the same as zero. Write those distinctions beside examples before starting the implementation.
The output is a new dictionary. Repeated normalized topics add together, and keys retain first appearance rather than alphabetical order. The caller still owns every input record. A function that strips by assigning into a record would break that ownership promise even if its printed totals looked right.
Build the first slice independently
First test empty input and one session. Then add duplicates, normalization, zero, and late invalid input. Keep parsing JSON and opening files outside this first function. The sample below isolates naming and order; it is not the whole analyser.
Browser-local values are enough to test these domain rules. Saving a report to disk or accepting a real command line needs a separately tested local adapter. Run the existing full reference later, then close it and reconstruct your own implementation; reading the solution does not complete the independent project.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
records = [{"topic": " loops ", "minutes": 0}Supply a zero-minute session whose topic needs trimming.
topics = [record["topic"].strip() for record in records]Read and trim into new strings without assigning into the records.
first_seen = list(dict.fromkeys(topics))Keep each normalized topic's first occurrence.
print(first_seen)Observe loops before lists, not sorted order.
Given study records with topic and minutes, produce totals per topic. Accept nonnegative integer minutes, including zero; reject missing/blank topics, negative values and booleans as minutes. Keep the input unchanged. The output preserves each topic's first appearance.
Conceptual project boundary, not a live execution trace
Conceptual reasoning steps for the original example, not a live trace of your edited Python.
- Caller recordsRead topic and minutes; never write into these records.
- Validate and normalizeReject invalid values before adding them to a private total.
- Owned reportReturn a new mapping in first-occurrence order; adapters format it later.
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.
Move the lists record first.
Try: Move that whole dictionary to the front of records.
first_seen becomes ['lists', 'loops'].
Keep a case difference.
Try: Change the final topic to "Loops".
It becomes a third spelling because strip does not lowercase.
Before you move on
For topics " Data ", "data", and "Data", how many output groups should this brief create?
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: "Data" and "data". Trimming joins the first and third sessions, but case folding was not requested.
Design before implementing
Separate checking a record from accumulating totals. Validation decides whether a value is allowed; aggregation combines allowed values.
Understand first
A single function that also reads files and prints progress is hard to test when a later row is invalid. A private accumulator can be discarded safely.
Words you will see
- Pure core
- A calculation with no external I/O or caller mutation.
- Accumulator
- Private state holding a result while it is being built.
- Fail fast
- Stop with an explicit error at the first unacceptable value.
Sequence work by dependency
Get the fields, validate their types and ranges, normalize the topic, then update the total. Do not update before validating the minutes. type(value) is int deliberately excludes bool because True is an int subclass but is not a study duration.
The example checks minute values in isolation. It returns a boolean only as a testing demonstration; the full analyser raises ValueError for invalid records. Keeping that distinction visible prevents accidentally changing the project's public error contract.
Define what failure leaves behind
A local totals dictionary may already contain earlier valid sessions when a later one fails. If it is never returned, logged as final, or stored outside the function, the caller receives no partial success. That does not roll back a file or database that another adapter already wrote.
Test invalid data after valid data as well as in the first position. Snapshot caller records before both successful and failing calls. This browser example needs no operating-system permissions. Publishing a report must wait for a complete result in a separately owned adapter.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
def valid_minutes(value):Name a small predicate used only in this demonstration.
return type(value) is int and value >= 0Require both the exact type and the nonnegative range.
allowed = [valid_minutes(value) for value in values]Check every value, including boolean and float lookalikes.
print(values)Show that checking did not change the supplied list.
Separate validation and aggregation. A dict is a natural lookup table for totals. A list of records preserves input order and repeated sessions. Decide what to do on invalid data: this project raises ValueError and does not return a partial report.
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 a valid large duration.
Try: Append 1000 to values.
The new validity flag is True; no maximum duration was specified.
Test a numeric string.
Try: Append "7" to values.
Its flag is False because external text parsing belongs to an adapter.
Before you move on
A valid five-minute record is followed by False minutes. Should the analyser return the first total?
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. False is not an allowed duration. Raise ValueError and return no report; the caller's records remain unchanged.
One complete working example
The complete in-memory analyser combines the earlier decisions: validate each session, normalize its topic, and accumulate a new report.
Understand first
A complete small slice lets you connect the brief to working source before adding unrelated delivery concerns.
Words you will see
- Lookup default
- A value used when a dictionary key is absent.
- First-occurrence order
- The order in which distinct normalized keys first enter the result.
- Output space
- Storage retained for the returned result.
Read the original implementation
study_totals starts with a fresh dictionary on each call. get reads missing fields as None. It rejects blank topics and invalid minute values, strips the valid topic, then adds to the prior total or zero. For lists, 20 plus 15 gives 35; loops contributes 10.
The two assertions cover empty input and the supplied sessions, not every requirement. The function assumes each record supports .get. An arbitrary integer record raises AttributeError rather than the promised domain ValueError; put a shape check at an external boundary if arbitrary records are supported.
Review costs and next evidence
For n records and k distinct topics, the ordinary dictionary model gives expected O(n) work and O(k) result storage when key lengths and integer sizes are bounded. Trimming long strings and adding very large integers also cost work. Streaming input does not bound the number of groups.
Add independent tests for whitespace, zero, booleans, invalid late records, order, and ownership. Recreate this slice without copying, then design a case of your own. This is browser-local standard-library-free computation; it neither saves a file nor proves a packaged application works.
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 new mapping per invocation.
topic = record.get("topic")Read a topic without changing its record.
topic = topic.strip()Rebind a local name to the normalized string.
totals[topic] = totals.get(topic, 0) + minutesAdd each valid session, retaining the key's first position.
Read the implementation, then recreate it in your own words. Afterwards change the data and add a new test. Studying this example is not an independently judged pass.
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.
Normalize another spelling.
Try: Change the last topic to " lists ".
The result remains lists 35 because stripping occurs before lookup.
Force a late validation failure.
Try: Change the last minutes value to True.
ValueError replaces final output; no partial report is returned.
Before you move on
Adding a final lists session with zero minutes changes which parts of the report?
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
Neither totals nor order change. Zero is valid and adds nothing; lists already has its first position.
A review before calling it done
Review means trying to disprove a requirement, not just rerunning the happy example. Ownership and ordering need their own observations.
Understand first
Dictionary equality ignores insertion order, and a correct-looking total can hide mutated input. Check each promised property directly.
Words you will see
- Regression test
- A case retained to catch a behavior breaking later.
- Snapshot
- A recorded value used for comparison after an operation.
- Identity
- Whether two names refer to the same object.
Choose observations that can fail
Compare list(result) to the expected topic order; comparing two dictionaries alone will not detect reordered keys. Compare a deep snapshot to caller records to catch nested mutation. Check a fresh result is not the input object when both happen to be mappings.
The sample uses a tiny local report to show separate order and identity checks. Equality verifies content while is verifies ownership. Returning a copy with the right values is useful; merely rebinding a second name to the caller's dictionary is not a copy.
Keep the review independent
Build a small acceptance table with one case per rule and a late failure after a valid record. Assert ValueError specifically rather than accepting any exception as success. A misspelled function that raises NameError must not pass a validation test.
Public exercise checks are transparent feedback, not exhaustive grading. After they pass, write a new adversarial case and explain the expected outcome before running it. No browser check verifies filesystem rollback or a deployed service; those need a future integration environment.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
supplied = {"loops": 2, "lists": 3}Supply an intentionally unsorted mapping.
before = supplied.copy()Snapshot these immutable integer values; nested data would need deeper comparison.
result = dict(supplied)Make a separate outer mapping.
print(result is supplied)Observe separate identity even though the values match.
Check empty input, repeated topics, surrounding whitespace, zero minutes, invalid minutes, blank topic and unchanged input. Document whether every record is assumed to be a dict. If records may be arbitrary values, add a shape check before .get.
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 only the report.
Try: Add result["loops"] = 9 before the prints.
Equality becomes False while supplied keeps 2.
Expose aliasing.
Try: Replace dict(supplied) with supplied.
The identity print becomes True, revealing shared ownership.
Before you move on
Two reports compare equal but one begins with lists and the other with loops. Have you checked the order requirement?
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. Dictionary equality compares key/value content. Compare list(report) with the required key sequence separately.
Specify the study-session boundary and ownership
The analyser accepts study records and returns topic totals without changing caller-owned input. Topic names must be nonblank strings after trimming; minutes must be exact nonnegative integers, including zero but excluding booleans. Output order follows each normalized topic's first appearance. State whether every record is assumed to be a dictionary. The reference calls .get directly, so arbitrary record objects need an additional shape-validation boundary rather than a claim that every malformed value already raises ValueError.
Separate a pure study_totals core from optional JSON, file, and command adapters. The core owns its output dictionary but not the input records. For the supplied sessions, lists accumulates 20 and 15 while loops contributes 10, producing lists 35 followed by loops 10. Normalizing surrounding whitespace before lookup means differently spaced spellings can intentionally combine; case folding is not part of the existing contract and should not be added accidentally.
Implement in numbered increments before reading the reference
1. Write tests for empty input and one valid record, then implement the smallest aggregation. 2. Add duplicate topics and first-occurrence ordering. 3. Add topic and minute validation before each update. 4. Add input-ownership assertions and only then consider external adapters. Keep each increment runnable so a failure can be traced to one new requirement rather than to a complete untested rewrite combining parsing, files, and domain logic.
Use type(minutes) is int because isinstance(True, int) is true and this domain does not treat booleans as durations. A local dictionary may contain intermediate totals when a later record fails, but raising without returning it preserves the function's no-partial-result contract. That is not equivalent to rolling back an external database or an already written file. Do not expose the accumulator or emit final-looking output while validation of later records can still fail.
Create a concrete acceptance and failure matrix
Unit cases should cover empty input, zero minutes, repeated topics, surrounding whitespace, a blank topic, missing fields, negative values, booleans, and noninteger numbers. Place an invalid record after a valid one and assert ValueError rather than a partial returned mapping. Keep a deep copy of nested representative input and compare after both successful and failing calls. Test order through the returned items, not only mapping equality, because equality alone does not establish insertion order.
For a JSON adapter, test malformed JSON separately from valid JSON with an invalid schema. For a CLI adapter, test stderr and nonzero exit status without changing the domain function's exceptions. File adapters need encoding, size policy, and closing on failure. These are future integration cases, not capabilities proved by the inline reference, which demonstrates a small in-memory aggregation and limited assertions rather than packaging, filesystem recovery, or deployment behavior.
Review costs and perform an independent transfer
With n records and k distinct normalized topics, expected aggregation time is O(n) and output storage is O(k) under bounded-size key and value assumptions. String trimming and hashing depend on topic length, and large accumulated integers are not fixed-size mathematical abstractions. A stream avoids retaining all records but still retains k groups. Set input, topic-length, and cardinality policies before describing the analyser as suitable for arbitrarily large reports.
Plan at least two focused work sessions: one to implement and test the pure contract without the reference, another after a gap to change a requirement and explain failures. Use progress by accepted cases rather than a promised universal completion time. If shape handling or external I/O remains unsupported, record that limit explicitly. Opening the worked solution or marking a lesson complete is not independent implementation evidence; reconstruct the reasoning and add a new case you designed yourself.
Transfer question: Extend the analyser to per-day totals. Which new contracts must be decided before grouping, and what would you test?
Define whether input supplies a calendar date or a timestamp, which timezone determines the study day, and how invalid or ambiguous local times are handled. Normalize that day before combining it with the normalized topic as a grouping key. Preserve the existing minute and ownership rules, and specify whether output order follows first occurrence or chronological order. Test records on either side of midnight in the chosen zone, duplicate day-topic pairs, invalid dates, and a late invalid record. This adds time semantics and potentially more distinct groups; it is not merely another dictionary field with unchanged memory assumptions.
Can you explain it?
Try from memory. Feedback stays on this page and does not award judged progress.
Transfer: count events per service
Independently implement event_counts. Count all occurrences, handle empty input and keep the original list unchanged. Add your own edge tests before opening the reference.
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.
Normalize owned study records
Guided increment 1: validate records and return fresh flat records containing only normalized topic and minutes.
The contract
- Input is a list; each record must be a dict with a nonblank exact str topic and exact nonnegative int minutes. Reject bool, missing fields and non-dicts with ValueError.
- Strip only surrounding topic whitespace; keep case and input order, including duplicates. Ignore extra fields.
- Return a new list and new dictionaries with only topic and minutes. Never mutate input, even on failure.
- Run this deterministic increment in browser Python with no external I/O. It is not a completed deployment or full independent 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.
Inspect 6 public checks
Transparent local learning checks, not exhaustive or tamper-proof grading.
- Trim and own
import copy supplied = [{"topic":" loops ","minutes":4,"extra":[]}] before = copy.deepcopy(supplied) result = normalize_sessions(supplied) expected = [{"topic":"loops","minutes":4}] assert type(result) is type(expected), "Wrong result type" assert result == expected, "Wrong result value" assert supplied == before, "Caller input changed" result[0]["topic"] = "changed" assert supplied == before, "Caller input changed through result alias" - Empty fresh output
import copy supplied = [] before = copy.deepcopy(supplied) result = normalize_sessions(supplied) expected = [] assert type(result) is type(expected), "Wrong result type" assert result == expected, "Wrong result value" assert supplied == before, "Caller input changed" assert result is not supplied, "Output must be owned"
- Keep repeated zero
import copy supplied = [{"topic":"a","minutes":0},{"topic":"a","minutes":2}] before = copy.deepcopy(supplied) result = normalize_sessions(supplied) expected = [{"topic":"a","minutes":0},{"topic":"a","minutes":2}] assert type(result) is type(expected), "Wrong result type" assert result == expected, "Wrong result value" assert supplied == before, "Caller input changed" - Boolean after valid
import copy supplied = [{"topic":"a","minutes":2},{"topic":"b","minutes":True}] before = copy.deepcopy(supplied) try: result = normalize_sessions(supplied) except ValueError: result = "ValueError" expected = "ValueError" assert type(result) is type(expected), "Wrong result type" assert result == expected, "Wrong result value" assert supplied == before, "Caller input changed" - Blank topic
import copy supplied = [{"topic":" ","minutes":1}] before = copy.deepcopy(supplied) try: result = normalize_sessions(supplied) except ValueError: result = "ValueError" expected = "ValueError" assert type(result) is type(expected), "Wrong result type" assert result == expected, "Wrong result value" assert supplied == before, "Caller input changed" - Invalid record shape
import copy supplied = [3] before = copy.deepcopy(supplied) try: result = normalize_sessions(supplied) except ValueError: result = "ValueError" expected = "ValueError" assert type(result) is type(expected), "Wrong result type" assert result == expected, "Wrong result value" assert supplied == before, "Caller input changed"
How does normalize owned study records support an independent project, and what remains untested?
Normalization checks schema and ownership before aggregation. Work is O(n) plus string lengths and output is O(n). Test the full analyser and external adapters separately; this increment does not publish a report.
Aggregate validated sessions
Guided increment 2: reuse validation and build a first-seen-order report without leaking intermediate totals.
The contract
- Use the normalize_sessions record rules, including ValueError for bad shapes and values.
- Return a fresh dict of normalized topics to summed minutes; empty gives {} and repeats accumulate.
- Preserve first normalized appearance order, case and caller input.
- Run this deterministic increment in browser Python with no external I/O. It is not a completed deployment or full independent 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.
Inspect 6 public checks
Transparent local learning checks, not exhaustive or tamper-proof grading.
- Duplicate accumulation
import copy supplied = [{"topic":"b","minutes":2},{"topic":"a","minutes":0},{"topic":" b ","minutes":3}] before = copy.deepcopy(supplied) result = session_totals(supplied) expected = {"b":5,"a":0} assert type(result) is type(expected), "Wrong result type" assert result == expected, "Wrong result value" assert supplied == before, "Caller input changed" assert list(result) == ["b", "a"], "Wrong key order" - Empty report
import copy supplied = [] before = copy.deepcopy(supplied) result = session_totals(supplied) expected = {} assert type(result) is type(expected), "Wrong result type" assert result == expected, "Wrong result value" assert supplied == before, "Caller input changed" - Case remains distinct
import copy supplied = [{"topic":"A","minutes":1},{"topic":"a","minutes":1}] before = copy.deepcopy(supplied) result = session_totals(supplied) expected = {"A":1,"a":1} assert type(result) is type(expected), "Wrong result type" assert result == expected, "Wrong result value" assert supplied == before, "Caller input changed" - Reject late negative
import copy supplied = [{"topic":"a","minutes":1},{"topic":"b","minutes":-1}] before = copy.deepcopy(supplied) try: result = session_totals(supplied) except ValueError: result = "ValueError" expected = "ValueError" assert type(result) is type(expected), "Wrong result type" assert result == expected, "Wrong result value" assert supplied == before, "Caller input changed" - Reject float
import copy supplied = [{"topic":"a","minutes":2.0}] before = copy.deepcopy(supplied) try: result = session_totals(supplied) except ValueError: result = "ValueError" expected = "ValueError" assert type(result) is type(expected), "Wrong result type" assert result == expected, "Wrong result value" assert supplied == before, "Caller input changed" - Reject missing field
import copy supplied = [{"topic":"a"}] before = copy.deepcopy(supplied) try: result = session_totals(supplied) except ValueError: result = "ValueError" expected = "ValueError" assert type(result) is type(expected), "Wrong result type" assert result == expected, "Wrong result value" assert supplied == before, "Caller input changed"
How does aggregate validated sessions support an independent project, and what remains untested?
Validation precedes aggregation, so no partial report escapes. This reuse retains normalized records in O(n) extra space; a full streaming implementation can validate one record at a time and retain O(k) totals. No adapter is built here.
Count qualifying sessions
Transfer: count sessions at or above a supplied threshold, rather than total their minutes.
The contract
- spec is (records, threshold); records obey normalize_sessions rules. Threshold is an exact nonnegative int; invalid threshold or records raise ValueError.
- Return a fresh dict counting only records with minutes >= threshold. Omit topics with no qualifying records.
- Validate all records even when below threshold. Order follows the first qualifying occurrence; no caller mutation.
- Run this deterministic increment in browser Python with no external I/O. It is not a completed deployment or full independent 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.
Inspect 6 public checks
Transparent local learning checks, not exhaustive or tamper-proof grading.
- Inclusive boundary
import copy supplied = ([{"topic":"a","minutes":5}],5) before = copy.deepcopy(supplied) result = qualifying_counts(supplied) expected = {"a":1} assert type(result) is type(expected), "Wrong result type" assert result == expected, "Wrong result value" assert supplied == before, "Caller input changed" - Empty records
import copy supplied = ([],0) before = copy.deepcopy(supplied) result = qualifying_counts(supplied) expected = {} assert type(result) is type(expected), "Wrong result type" assert result == expected, "Wrong result value" assert supplied == before, "Caller input changed" - Qualifying order and repeats
import copy supplied = ([{"topic":"a","minutes":1},{"topic":"b","minutes":5},{"topic":"a","minutes":5},{"topic":"b","minutes":8}],5) before = copy.deepcopy(supplied) result = qualifying_counts(supplied) expected = {"b":2,"a":1} assert type(result) is type(expected), "Wrong result type" assert result == expected, "Wrong result value" assert supplied == before, "Caller input changed" assert list(result) == ["b", "a"], "Wrong qualifying order" - Zero qualifies
import copy supplied = ([{"topic":"z","minutes":0}],0) before = copy.deepcopy(supplied) result = qualifying_counts(supplied) expected = {"z":1} assert type(result) is type(expected), "Wrong result type" assert result == expected, "Wrong result value" assert supplied == before, "Caller input changed" - Invalid filtered record
import copy supplied = ([{"topic":"a","minutes":-1}],5) before = copy.deepcopy(supplied) try: result = qualifying_counts(supplied) except ValueError: result = "ValueError" expected = "ValueError" assert type(result) is type(expected), "Wrong result type" assert result == expected, "Wrong result value" assert supplied == before, "Caller input changed" - Boolean threshold
import copy supplied = ([],True) before = copy.deepcopy(supplied) try: result = qualifying_counts(supplied) except ValueError: result = "ValueError" expected = "ValueError" assert type(result) is type(expected), "Wrong result type" assert result == expected, "Wrong result value" assert supplied == before, "Caller input changed"
How does count qualifying sessions support an independent project, and what remains untested?
The changed reducer counts occurrences and introduces an inclusive threshold. Normalization still costs O(n) retained records in this solution. Independent full-project work should add its own cases and adapters; this is only a transfer slice.
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 milestoneExtend the requirements deliberately
An adapter converts an external representation into the domain's input or output. Keep that conversion separate from the aggregation rules.
Understand first
JSON text, file paths and CLI arguments fail in different ways. Separating them lets the same analyser remain testable without disks or commands.
Words you will see
- Adapter
- Code translating between an external boundary and a core contract.
- Schema
- The expected shape and types of data.
- Serialization
- Encoding values as text or bytes.
Extend one boundary at a time
JSON parsing proves only that text is valid JSON. A decoded dictionary is not automatically a valid list of study records. Check the outer shape, then record shapes, then the domain values. Give syntax errors and schema errors distinct explanations without dumping private input.
The sample decodes an in-memory JSON array and inspects a field. It does not claim to implement a complete JSON adapter. A real adapter should call the tested analyser only after its shape policy is satisfied and should serialize only a complete result.
Do not confuse local and browser capabilities
Browser-local JSON text needs no file access and is deterministic. A local file adapter additionally owns encoding, size limits, allowed paths and closing the resource on errors. Publishing output needs a replacement policy so a failed run does not overwrite a good report.
For a CLI, translate expected input errors into documented stderr and exit behavior at the entry point, not inside study_totals. Test the pure core first, the in-process adapter second, and real file/installed-command behavior later. These project increments are not a deployment claim.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
import jsonUse the standard-library decoder, with no package installation.
records = json.loads(text)Decode supplied text without reading a file.
if type(records) is not list:Check one schema boundary after syntax decoding.
print(records[0]["minutes"])Observe a field; full record validation is still separate.
Add JSON file input, stable sorted reporting, per-day totals and a command-line interface as separate changes. Separate I/O from the pure aggregation so tests do not need disk access. Introduce type/schema validation at the external boundary.
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 outer shape.
Try: Replace the JSON array with {"topic": "loops"}.
The explicit shape check raises ValueError.
Change a field type.
Try: Use "minutes": "4" in the JSON text.
The print still displays 4; later exact-type domain validation must reject the string.
Before you move on
The JSON text {"topic":"loops"} decodes successfully. Is it a valid top-level input here?
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. It is an object, not the required array. Schema validation must reject it before iterating study records.
Come back after a gap
Transfer changes a rule, not just the sample names. Rebuild the design when the output means something different.
Understand first
Counting events per service resembles adding minutes but each occurrence contributes one. Recognizing the changed unit prevents copying the wrong arithmetic.
Words you will see
- Transfer
- Applying an idea to a changed requirement without following the reference.
- Unit
- What a number measures, such as minutes or event occurrences.
- Reflection
- Explaining a choice and its limits after trying it.
Plan a delayed independent session
After a gap, close the study solution and write event_counts from a blank function. Input is an ordered list of service names; output counts all occurrences in first-seen order. Empty input gives an empty mapping. No minute field or duration validation belongs in this changed problem.
Before implementation, predict api, worker, api as api 2 then worker 1. Add your own empty, repeated and ownership cases. Explain why a set would lose counts and why sorting would change an order promise. The original course challenge remains a separate independent task.
Review evidence without overclaiming
The sample below counts events and makes the changed unit visible. For n names and k distinct names, expected dictionary work is O(n) and output space O(k) with bounded name sizes. Input remains borrowed; output is newly owned.
An in-memory count can run in browser Python. Reading service logs, parsing timestamps and handling time zones would be further contracts with local adapters. A matching sample, revealed answer or self-reported checkpoint is not evidence that you independently built and deployed a log analyser.
The original example, step by step
These steps explain the original code below. They do not change when you edit your own experiment.
services = ["api", "worker", "api"]Supply three events, including a repeated service.
counts = {}Own a separate output mapping.
counts[service] = counts.get(service, 0) + 1Add one occurrence, not a duration read from a record.
print(services)Show the borrowed event sequence is unchanged.
After at least a day, implement a related problem without the reference: total spending per category, or count errors per service. Explain why a dict fits, what assumptions change and how you would test it. A self-reported checkpoint is evidence of reflection, not a hiring-readiness score.
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 an event for the first service.
Try: Append "api" to services.
api becomes 3 and stays first.
Try the empty boundary.
Try: Replace services with [].
The new output is {} and the original empty list stays empty.
Before you move on
For worker, worker, api, worker, what result and key order should event counting produce?
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 3 then api 1. Each event adds one; worker appeared first even though api sorts earlier.
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.