Solving a Simpler Version First
Concepts covered: 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
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
With a single user's days already sorted and no repeats, the core idea fits in one comparison: if a day is exactly 1 more than the day before it, the current run grows; otherwise the run ends and a new one starts. The program collects every run length and takes the largest at the end.
days = [1, 2, 3, 5, 6, 10]
runs = []
current = 1
for i in range(1, len(days)):
if days[i] == days[i - 1] + 1:
current += 1
else:
runs.append(current)
current = 1
runs.append(current)
print(runs)
print(max(runs))[3, 2, 1] 3
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.
def longest_streak(days):
if len(days) == 0:
return 0
days = sorted(days)
runs = []
current = 1
for i in range(1, len(days)):
gap = days[i] - days[i - 1]
if gap == 0:
continue
if gap == 1:
current += 1
else:
runs.append(current)
current = 1
runs.append(current)
return max(runs)
events = [("ana", 3), ("bo", 1), ("ana", 1), ("ana", 2),
("bo", 2), ("ana", 2), ("bo", 5)]
by_user = {}
for user, day in events:
if user not in by_user:
by_user[user] = []
by_user[user].append(day)
for user, days in by_user.items():
print(user, longest_streak(days))Output:
ana 3 bo 2
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.
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?
- Sort all rows by revenue and print the top row for the whole table
- For one region's (hour, revenue) rows, total each hour in a dict and pick the top hour
- Handle every region at once, but skip hours that have no revenue
- Write guard clauses for every malformed row before anything else
When an added difficulty breaks an earlier version, list each kind of input the difficulty brings and the branch it reaches in the old code. For the streak loop, those inputs are the possible gaps between neighboring days. Version 1 has only 2 branches, so every gap that is not 1 lands in the branch that closes the run.
| 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 |
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.