Python lab (live judge)
These run your code in real Python against hidden-style tests. stdin β stdout problems compare your output line by line (trailing spaces are ignored); function problems call your function directly. Press Tab / Shift+Tab to indent and Ctrl+Enter to run.
Read input from sys.stdin (read(), buffer.read(), readline(), or input()).
open(0) is not supported here. On the PHP-hosted version your code runs in your browser (Pyodide). The first run downloads the runtime, about 10 MB.
Think like the judge: after the samples pass, ask yourself what's the empty case, what are the ties, what happens with a 10βΆ-row input? Each exercise has at least one hidden-style edge case.
Warm-up
Fast IO warm-up: totals per user
stdin β stdoutβ solvedn, then n lines user_id,amount
(amount is a decimal, may be negative for refunds; lines may have surrounding spaces).Output: one line per user
user_id total sorted by user_id as a string, total with exactly 2 decimals.Flatten nested JSON
implement flatten()β solvedflatten(obj): turn nested dicts/lists into a flat dict with dot-joined keys.
List elements use their index. Empty dicts/lists are kept as values. Example:{"a": {"b": 1, "c": [10, {"d": 2}]}, "e": {}} β
{"a.b": 1, "a.c.0": 10, "a.c.1.d": 2, "e": {}}Deduplicate CDC records
implement dedupe_latest()β solveddedupe_latest(records): records are dicts with keys id, updated_at
(ISO string) and other fields. Keep, for each id, the record with the greatest updated_at; if two
records tie, keep the one that appears later in the input. Return the list sorted by id.Merge overlapping intervals
implement merge_intervals()β solvedmerge_intervals(intervals): intervals is an unsorted list of
(start, end) pairs. Merge every pair that overlaps or touches ((1, 5) and (5, 7) β
(1, 7)). Return a list of tuples sorted by start.Pipeline logic
Sessionize events
implement sessionize()β solvedsessionize(events, gap): events is an unsorted list of (user, ts) with ts in seconds.
A new session starts when the gap to the user's previous event is strictly greater than gap.
Return a list of (user, start, end, count) sorted by user then start.Schema validation / data quality
implement validate()β solvedvalidate(rows, schema). schema maps column β (type, required), type in
"int" | "float" | "str". For each row (index i) and each schema column (in schema order) report:
(i, col, "missing")if the key is absent or None and the column is required (optional missing β fine)(i, col, "type")if present but wrong type.intaccepts ints but not bools;floataccepts int or float (not bool);straccepts str.(i, col, "unknown")for each key not in the schema β reported after schema columns, keys sorted.
Log parsing: top-K endpoints
stdin β stdoutβ solvedK. Then access-log lines until EOF, e.g.
10.0.0.1 - - [23/Oct/2026:10:00:01 +0330] "GET /api/orders?id=3 HTTP/1.1" 200 512.
Some lines are malformed β skip them. Count requests per path without query string.
Print the top K as path hits errors where errors = number of 5xx responses. Sort by hits desc, then path asc.pandas: customer summary
implement customer_summary()β solvedcustomer_summary(df): df has columns customer_id, order_date (string YYYY-MM-DD),
amount, status. Using only status == "completed" rows, return a DataFrame with columns
customer_id, orders, total, first_order, last_order (dates as strings), sorted by total desc then customer_id asc,
with a fresh 0..n-1 index. (The judge compares df.to_dict("records").)As-of join: price at trade time
implement asof_join()β solvedasof_join(trades, rates): trades is a list of (ts, amount),
rates an unsorted list of (ts, rate). For every trade, in input order, return
round(amount * rate, 2) using the latest rate whose ts is <= the trade's ts, or None if no
such rate exists. Aim for O((n + m) log m).LRU cache simulation
implement lru_simulate()β solvedlru_simulate(capacity, requests): simulate an LRU cache of size capacity over a
list of keys. A request for a cached key is a hit (and makes it most recently used); otherwise it's a miss,
the key is inserted, and if the cache is over capacity the least recently used key is evicted. Return
(hits, misses, keys) where keys is the final cache content from least to most recently used.Peak concurrent sessions (sweep line)
implement peak_concurrency()β solvedpeak_concurrency(sessions): each session is a half-open interval [start, end), so a
session ending at t does not overlap one starting at t. Return
(peak, first_time): the maximum number of simultaneous sessions and the earliest time that maximum is reached.
For no sessions return (0, None).Hard
Pipeline DAG: execution order
implement run_order()β solvedrun_order(deps): deps maps task β list of tasks it depends on (dependencies may not
appear as keys themselves). Return an execution order where every task comes after its dependencies, choosing
the alphabetically smallest available task at each step. If there is a cycle return None.Slowly Changing Dimension type 2
implement apply_scd2()β solvedapply_scd2(dim, changes). dim: list of rows
{"id", "attr", "valid_from", "valid_to"} (current row has valid_to=None).
changes: list of (id, attr, date) β process them in date order (stable for equal dates):
- unknown id β insert a new current row (valid_from=date)
- current attr differs β close current row (
valid_to=date) and insert a new current row - same attr β no-op (idempotent!)
Reading a failing test
- your output is empty β you never printed, printed inside a function you didn't call, or crashed before the final write (check error).
- Output matches except the last lines β you forgot to flush the final group (the "last session" bug).
gotshows[[1, 2]]butexpectedshows[(1, 2)]β tuples vs lists. A judge comparing with==treats them as different.Nonereturned β you built the result but forgotreturn.KeyError/IndexErroron the empty test β guardlines[0]and empty lists before indexing.
Finished the lab? Go to the Mock contest lesson for six new problems against the clock.