Sub topic 5
Finding the longest streak
This chapter adds the second streak metric to the tracker: the longest run of consecutive days a habit has ever been done. It assumes you know basic Python (functions, sets, loops), the datetime module's date and timedelta, and the check-in model from earlier chapters, where each habit maps to a set of dates.
Why the longest streak matters
The current streak tells you how you are doing now. The longest streak tells you what you have already shown you can do. Together they answer a useful question: is today's streak a new low, an ordinary stretch, or a personal best?
The longest streak never decreases when you miss a day. It only grows when a current run passes the old record. That makes it a good motivator and a good input for reviewing a habit later.
The idea: sort, then compare neighbors
A set has no order, so you cannot look at "the next day" directly. The fix is to sort the dates first. Once they are in order, two dates belong to the same run exactly when the later one is one day after the earlier one.
The algorithm makes one pass over the sorted dates:
- Keep a
runcounter for the current run and abestcounter for the longest run seen so far. - For each date, compare it with the previous date.
- If the gap is exactly one day, add 1 to
run. Otherwise start a new run at 1. - After each date, update
bestifrunis larger.
The code
from datetime import timedelta
def longest_streak(days):
best = run = 0
previous = None
for day in sorted(days):
if previous is not None and day - previous == timedelta(days=1):
run += 1
else:
run = 1
best = max(best, run)
previous = day
return bestSubtracting two date objects gives a timedelta, so day - previous == timedelta(days=1) is a direct test for "the very next day". The first date has no previous date, so previous is not None makes it start a run of 1.
A worked example
Suppose a habit was done on these dates:
from datetime import date
days = {
date(2026, 11, 1),
date(2026, 11, 2),
date(2026, 11, 3),
date(2026, 11, 5),
date(2026, 11, 6),
date(2026, 11, 10),
}Run longest_streak on this set, with the function defined as above. The loop works like this:
| Date | Gap from previous | `run` | `best` |
|---|---|---|---|
| Nov 1 | none | 1 | 1 |
| Nov 2 | 1 day | 2 | 2 |
| Nov 3 | 1 day | 3 | 3 |
| Nov 5 | 2 days | 1 | 3 |
| Nov 6 | 1 day | 2 | 3 |
| Nov 10 | 4 days | 1 | 3 |
The function returns 3. The best value survives the later resets because it is only ever replaced by something larger.
Common errors
- Forgetting to sort. Iterating over the set directly gives arbitrary order, so neighbors are not consecutive days. The result looks plausible on small data and is wrong on real data.
- Resetting to 0 instead of 1. When a gap breaks the run, the current date still counts as a day done. Starting a new run at 0 undercounts every run after the first by one.
- Using
>= 1day instead of== 1day. A gap of five days is not a streak. Test for exactly one day. - Updating
bestonly when the run grows. If you skip the update after a reset, a habit whose longest run is a single day returns 0. Updatingbeston every iteration avoids that. - Counting duplicates. This is not a problem here, because a set holds each date once. It is one more reason the earlier chapters store check-ins in a set instead of a list.
Testing it
A few assert lines catch most mistakes. Include the edge cases: empty, one day, and a record that is not the first run.
from datetime import date, timedelta
def longest_streak(days):
best = run = 0
previous = None
for day in sorted(days):
if previous is not None and day - previous == timedelta(days=1):
run += 1
else:
run = 1
best = max(best, run)
previous = day
return best
start = date(2026, 11, 1)
assert longest_streak(set()) == 0
assert longest_streak({start}) == 1
assert longest_streak({start, start + timedelta(days=2)}) == 1
assert longest_streak({start + timedelta(days=i) for i in range(5)}) == 5
# The record is the second run, not the first.
second_run_record = {start, start + timedelta(days=1)} | {
start + timedelta(days=10 + i) for i in range(4)
}
assert longest_streak(second_run_record) == 4
print("all checks passed")Cost and how it relates to the current streak
Sorting dominates the cost, so the function runs in O(n log n) time for n check-ins. For a personal tracker with a few thousand dates this is instant.
current_streak and longest_streak answer different questions. The current streak starts at today (or yesterday) and walks backwards, so it only looks at the most recent run. The longest streak scans the whole history. The current streak can never exceed the longest streak. If your two numbers are equal, you are on your personal best right now.
Exercise
A habit has check-ins on Dec 1, Dec 2, Dec 4, Dec 5, Dec 6 and Dec 7. What does longest_streak return, and what would it return if the bug "reset the run to 0 instead of 1 on a gap" were introduced?
Show answer
The correct function returns 4, for the run Dec 4 to Dec 7. With the bug, Dec 1 starts at 1 (the first date has no previous date) and Dec 2 makes it 2. Dec 4 is a gap, so run becomes 0 and then Dec 5, 6 and 7 count 1, 2, 3 only if the code adds on later days. That gives a best of 3 for the Dec 4 to Dec 7 run, one less than the true value of 4.
Exercise
Write a short function that returns the start and end dates of the longest streak instead of only its length. Which variables do you need to add to longest_streak?
Show answer
Track the start of the current run and the start and end of the best run. When a gap occurs, set runstart to the current day. After updating run, if run is greater than best, set best, beststart = runstart and bestend = day. Return (beststart, bestend), or None for an empty set.