Problem Solving: Intermediate
A share needs the total first
The first loop prints nothing. Its only job is to produce total, and the second loop reads that value on every row. Every 2-pass solution has this shape: pass 1 builds a small summary, and pass 2 makes each row's decision using it.
When the summary is a dict of counts
The summary can be bigger than a single number. Suppose an event log lists the user behind each event, and the task is the first user who appears exactly once, a one-time visitor. When the loop reaches cy, it cannot tell whether cy shows up again 3 rows later. Pass 1 counts every user into a dict; pass 2 walks the log in its original order and stops at the first user whose count is 1.
1events = ["ana", "bo", "ana", "cy", "bo", "dee"]23counts = {}4for user in events:5 counts[user] = counts.get(user, 0) + 167first_once = None8for user in events:9 if counts[user] == 1:10 first_once = user11 break1213print(counts)14print(first_once)
Pass 1 fills counts; pass 2 stops at the first user counted once.
The dict is complete before the second loop asks its first question, so counts[user] == 1 is a statement about the entire log. The second pass could walk counts instead, because a dict keeps its keys in first-inserted order and a user seen once was inserted at its only position. Either loop works; neither can run until the counting is finished.
Spotting a problem that needs 2 passes
- The answer for a row depends only on rows already read
- Running totals, a maximum, a count of rows over a threshold
- Example: print the cumulative minutes after each play
- A row's answer depends on rows that come after it
- Shares of a total, distance from the average, 'appears only once'
- Example: flag every order larger than the day's average order
Which task needs a second pass over a list of order amounts?
An average adds one line between the 2 passes. Pass 1 adds into total. Once that loop has finished, average = total / len(amounts) runs a single time, outside both loops, and pass 2 compares each amount with that fixed value. For orders [40, 10, 30, 80], pass 1 ends with total at 160 and average at 40.0, and pass 2 flags only 80, because > leaves out the 40 that equals it. Indented one level deeper, inside pass 1, the division becomes a running average that changes on every row and matches the real one only after the last row.
Where an unguarded function breaks
What does this program print?
| Input kind | Example | What average does |
|---|---|---|
| Empty | `[]` | ZeroDivisionError |
| None | `None` | TypeError from `sum` |
| Wrong container | `"468"` | TypeError from `sum` |
| Bad item | `[4, "8", 6]` | TypeError from `sum` |
| Single item | `[7]` | 7.0, correct |
| Booleans | `[True, False]` | 0.5, counted as 1 and 0 without complaint |
Guard clauses that return a deliberate answer
A guard clause checks for a bad case at the top of the function and returns immediately. The design question is what to return. For an average of nothing, 0 would be a lie: a dashboard would plot 0 minutes for a listener with no data, and nobody downstream could tell it from a real 0. None says 'no answer exists' and forces the caller to check with is None.
isinstance(None, list) is False, so the first guard catches None along with strings and dicts. The order of guards matters: each check must be safe to run on whatever the earlier checks let through. Put the len check first and average(None) crashes with TypeError: object of type 'NoneType' has no len() before the type check ever runs.
Bad items inside a good list
A type check on the list says nothing about its items. A batch of watch times may carry a string that was never converted, or a None where a client failed to report. The function faces a policy choice: reject the whole batch, or skip the bad items. Skipping keeps the pipeline moving, but a silent skip hides data loss, so the version below returns the count of dropped items alongside the average.
The final guard, good == 0, catches a case the type checks cannot: a real list in which every item was bad. Without it, ["x"] reaches total / good and divides by zero, the empty-list crash arriving by a different road.
- Decide the return value for empty, None and wrong-type input before writing the main logic
- Order guards so each check is safe on what earlier checks let through
- Report how many items were skipped instead of dropping them silently
- Test every function on [], None and a 1-item list
- Return 0 for 'no data' when 0 is also a real answer
- Call len() on a value that may be None
- Assume a list of the right type holds items of the right type
- Guard only the case that crashed last week
Count steps, then compare with a budget
A loop over n items runs its body n times, and 2 passes run 2 × n bodies. A loop inside a loop that compares every item with every later item runs about n × n ÷ 2 bodies, because the first item is compared with n - 1 others, the second with n - 2, and so on. For a working budget, take around 10 million simple steps per second in Python: a conservative figure for loop bodies doing a comparison or an addition, which you can confirm by timing a loop on your own machine.
1ids = [7, 3, 9, 3, 5, 8]23pair_checks = 04dup_nested = False5for i in range(len(ids)):6 for j in range(i + 1, len(ids)):7 pair_checks += 18 if ids[i] == ids[j]:9 dup_nested = True1011dict_steps = 012counts = {}13for x in ids:14 dict_steps += 115 counts[x] = counts.get(x, 0) + 11617print(pair_checks, dup_nested)18print(dict_steps, counts)
Pair checks grow with n × n; counting steps grow with n.
| n (items) | Steps, 1 pass | Time, 1 pass | Pair checks | Time, pair checks |
|---|---|---|---|---|
| 1,000 | 1,000 | 0.0001 s | 499,500 | 0.05 s |
| 100,000 | 100,000 | 0.01 s | about 5 billion | about 8 minutes |
| 10,000,000 | 10,000,000 | 1 s | about 50 trillion | about 58 days |
Small limits allow the direct approach
Loops hidden inside a single line
Some loops do not look like loops. x in some_list, some_list.count(x), some_list.index(x) and some_list.remove(x) each scan the list from the front, so calling one inside a for loop builds a loop inside a loop. The dedup below has a single visible for, but user not in seen walks seen on every row.
With 1 million mostly distinct users, seen grows toward 1 million names, and each later row scans most of it: hundreds of billions of comparisons. A dict behaves differently. key in counts and counts[key] take about the same time whether the dict holds 10 keys or 10 million, which is why the counting pass in the animation stays at n steps.
- ▸Up to around 1,000 items: comparing every pair fits, so pick the clearest code
- ▸Up to around 100,000 items: 1 or a few passes, with dict lookups inside
- ▸About 10 million items: a few passes at most, and watch what each pass stores
- ▸A time limit is a step budget: about 10 million simple steps per second
- ▸Count the hidden scans from in, count, index and remove as loops
A task gives up to 200,000 transactions and expects an answer in about 1 second. With a budget of 10 million simple steps per second, which approach is ruled out before coding?
The pair count has an exact form. The first item meets n - 1 later items, the second n - 2, down to 0 for the last, and those add up to n * (n - 1) // 2. For the 6 IDs in the animation that is 6 × 5 ÷ 2 = 15, the pair_checks it printed; for 1,000 items it is 499,500, the figure in the table. Turning a limit into a verdict is then one comparison: compute the steps for the largest allowed n and check whether they stay within the budget, 10 million steps for a 1-second limit.
The full problem: longest streak per user
A product team wants each user's longest run of consecutive active days. The events arrive as (user, day) tuples, where day is a day number. They are out of order, a user can be active twice on the same day, and many users share a single list. That is 3 complications on top of the core question.
| Version | What it drops | What it teaches |
|---|---|---|
| 1 | Many users, disorder, repeat days | A streak breaks wherever 2 neighbors differ by more than 1 |
| 2 | Many users, disorder | A gap of 0 is a repeat day: skip it, neither extend nor break |
| 3 | Many users | Sorting the days first turns disorder into version 2 |
| 4 | Nothing | Group by user, then call the single-user function per user |
Version 1: a single user, sorted, no repeats
1days = [1, 2, 3, 5, 6, 10]23runs = []4current = 15for i in range(1, len(days)):6 if days[i] == days[i - 1] + 1:7 current += 18 else:9 runs.append(current)10 current = 111runs.append(current)1213print(runs)14print(max(runs))
A run grows while each day is 1 more than the last and closes at every gap.
Day 5 follows day 3, so the first run closes at 3 and a new run starts. Day 10 follows day 6 and closes a run of 2. The runs.append(current) after the loop records the last run, which no gap ever closed.
Versions 2 to 4: add a difficulty at a time
Version 2 adds repeat days. With [1, 2, 2, 3], version 1 sees 2 followed by 2, a difference of 0, and wrongly closes the run. Computing gap = days[i] - days[i - 1] and skipping when gap == 0 repairs it. Version 3 adds disorder, and sorted(days) at the top reduces it to version 2. Version 4 adds many users: group the days into a dict of lists keyed by user, then call the finished single-user function once per key.
Each version kept the earlier tests valid. Version 1's sample still returns 3 under the final code, and ana's days [3, 1, 2, 2] exercise both the sort and the repeat skip. The empty-list guard came from running the version 1 logic on an input it never saw: with no days the loop does not run, and the trailing append would report a streak of 1.
- ▸Solve for 1 user, 1 key or 1 day before many
- ▸Assume the input is sorted, then sort it yourself later
- ▸Assume no duplicates, then decide what a duplicate should mean
- ▸Fix the size at 3 or 4 items and work the answer by hand
- ▸Drop the output format and print raw values until the logic is right
The full task: for each region, find the hour with the highest total revenue, from rows of (region, hour, revenue) in no particular order. Which simpler version is the best first step?
| Gap between neighbors | Version 1 branch | Right behavior |
|---|---|---|
| 1 | `if`: the run grows | Grow the run, as version 1 does |
| 0, a repeat day | `else`: the run closes | Skip the row |
| 2 or more | `else`: the run closes | Close the run, as version 1 does |
Finding the first one-time user with count() and with a dict
Both print cy. first_once_count is 4 lines and says what it means: the first user whose count in the log is 1. Its cost hides in events.count(user), which reads the whole list on every call. first_once_dict takes 2 loops and a dict, and reads the log exactly twice.
Speed, memory and clarity side by side
| Measure | first_once_count | first_once_dict |
|---|---|---|
| Reads of a log with no one-time user | n × n | 2 × n |
| n = 1,000 | 1,000,000 reads | 2,000 reads |
| n = 100,000 | 10 billion reads, about 17 minutes | 200,000 reads, about 0.02 s |
| Extra memory | Nothing beyond the list | One dict entry per distinct user |
| Clarity | Mirrors the task in a single condition | Two loops; the reader must see why |
The table assumes a log with no one-time user, the input that makes both functions read to the end. There the count version calls count n times, each a full scan, while the dict version finishes its 2 passes and returns None. The times use the same budget as before, 10 million simple steps per second.
A rule for choosing
- The log is capped at roughly 1,000 events
- The function runs once in a script, not once per row of a pipeline
- Readers need to check it against the spec at a glance
- The log can reach 100,000 events or more
- The function runs inside a loop over many logs
- The next request, every one-time user, needs the counts anyway
A nightly job checks a config list capped at 50 entries for any name that appears twice. One correct version calls names.count(name) > 1 inside a loop; another builds a dict of counts first. Which should the team keep?
The count version has a second flaw once the task changes from 'is there a duplicate' to 'list the duplicates'. A loop over ids that prints every ID passing ids.count(i) > 1 prints it once per appearance, so an ID that occurs 3 times prints 3 times. Walking the dict of counts visits each key exactly once, in the order it was first inserted, which is the order of its first appearance in the list. Counting in pass 1 and filtering the dict in pass 2 gives one line per duplicated ID.
> Spotify's Wrapped shows each listener their top artist and the minutes they spent with that artist over the year. A batch job has to turn a log of (listener, artist, minutes) rows into a card per listener, including listeners who signed up recently and have no plays, with every card's share computed correctly.
in, count, index and remove on a list each hide a scan, and inside a loop they make a nested loop.Two passes, guarded inputs, size budgets and simpler drafts: habits that pick a solution before you type it.
- Category
- Python
- Difficulty
- intermediate
- Duration
- 21 minutes
- Challenges
- 18 hands-on challenges
Topics covered: Solving a Problem in 2 Passes, Edge Case Handling, What Input Size Rules Out, Solving a Simpler Version First, Comparing 2 Working Solutions
Lesson Sections
- Solving a Problem in 2 Passes (concepts: List Comprehension)
Some questions about a list can be answered row by row. Others depend on a fact about the whole list: its total, its average, or how often a value occurs. For those, the loop meets row 1 before it has read the rows that decide row 1's answer. The way out is to read the data twice: a first pass that only learns a summary, then a second pass that acts on every row. A share needs the total first Take 4 play events for a single listener, each an artist and the minutes played. The task is to print wh
- Edge Case Handling (concepts: Guard Clauses)
A function that works on the inputs its author pictured is half finished. Pipelines hand functions empty batches, missing values, strings where numbers were expected and lists of a single row. An edge case is an input at the boundary of what the function was written for, and each one either gets a deliberate answer or produces a crash or a silent wrong number. Where an unguarded function breaks Empty is only one boundary. The table lists the inputs worth asking about for any function that takes
- What Input Size Rules Out (concepts: Sets)
A problem statement often says how big the input can get: up to 1,000 rows, up to 100,000 events, an answer within 1 second. Those limits are design information. Before writing code, you can estimate how many steps each candidate approach takes and discard the ones that cannot finish in time. Count steps, then compare with a budget The animation runs 2 approaches to a duplicate check on 6 IDs and counts the steps each one takes. At 6 IDs the gap is 15 against 6. The table pushes n to sizes a pip
- Solving a Simpler Version First (concepts: Generators)
Some problems arrive with several difficulties tangled together. Handling all of them in the first draft produces code that is wrong in ways that are hard to locate. A better move is to strip the problem down to a version small enough to work by hand, solve it, and then add the difficulties back one at a time, testing after each. The full problem: longest streak per user Version 1: a single user, sorted, no repeats With a single user's days already sorted and no repeats, the core idea fits in on
- Comparing 2 Working Solutions (concepts: Collections)
Solutions that both pass every test can still differ in what they cost. One may finish in a fraction of a second where the other takes minutes, one may hold an extra dict the size of the input, and one may read like the problem statement while the other needs explaining. Choosing between them is a judgment made against the input limits and the people who will maintain the code. Finding the first one-time user with count() and with a dict Speed, memory and clarity side by side A rule for choosing