Solving a Problem in 2 Passes

Concepts covered: 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 what percent of the listener's minutes each event represents. A percent is minutes divided by the total, and the total stays unknown until the last row has been read. Here is a 1-pass attempt that divides by the total seen so far:

plays = [("Mitski", 60), ("SZA", 20), ("Mitski", 40), ("Khruangbin", 80)]

running = 0
for artist, minutes in plays:
    running += minutes
    print(artist, minutes * 100 // running)

Output:

Mitski 100
SZA 25
Mitski 33
Khruangbin 40

Only Khruangbin's line is right. Every earlier row was divided by a partial total: Mitski's first 60 minutes looked like 100% because nothing else had been read yet. No change to the arithmetic inside that loop can repair it, since the missing information sits in rows the loop hasn't reached.

plays = [("Mitski", 60), ("SZA", 20), ("Mitski", 40), ("Khruangbin", 80)]

total = 0
for artist, minutes in plays:
    total += minutes

for artist, minutes in plays:
    print(artist, minutes * 100 // total)

Output:

Mitski 30
SZA 10
Mitski 20
Khruangbin 40

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.

events = ["ana", "bo", "ana", "cy", "bo", "dee"]

counts = {}
for user in events:
    counts[user] = counts.get(user, 0) + 1

first_once = None
for user in events:
    if counts[user] == 1:
        first_once = user
        break

print(counts)
print(first_once)
{'ana': 2, 'bo': 2, 'cy': 1, 'dee': 1}
cy

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

One pass is enough when
  • 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 second pass is needed when
  • 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

Reading twice doubles the row visits, so 1 million rows become 2 million, and the summary from pass 1 must fit in memory. A single number costs nothing; a dict of counts grows with the number of distinct users. Both costs grow in step with the data, which keeps 2-pass solutions practical on large inputs.

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.

About this lesson

This section is part of the Problem Solving: Intermediate lesson on DataDriven, the home of data engineering. Lessons cover SQL, Python, Spark, data modeling and pipeline architecture, and each section pairs its explanation with worked examples and practice you run as you go.