Sub topic 2
Calculating Habit Streaks and Completion
Assume you know Python functions, dictionaries, sets, loops, date, timedelta, and basic text-file operations. The tracker stores each habit as a set of dates. A set prevents duplicate check-ins on the same day.
Calculating the Current Streak
A current streak is the number of consecutive logged days ending today, or yesterday when today has not been logged yet. This prevents a streak from appearing broken halfway through the day.
from datetime import date, timedelta
def current_streak(days, today=None):
today = today or date.today()
day = today if today in days else today - timedelta(days=1)
streak = 0
while day in days:
streak += 1
day -= timedelta(days=1)
return streak
logged = {
date(2026, 11, 25),
date(2026, 11, 26),
}
print(current_streak(logged, date(2026, 11, 27))) # 2The loop stops at the first missing date. A missed day therefore ends the current streak.
Finding the Longest Streak
The longest streak describes the best consecutive run anywhere in the history. Sort the dates, then extend the run only when the next date is exactly one day later.
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 bestMeasuring Completion Rate
A completion rate measures logged days in a fixed window. For a 30-day window, divide the number of logged dates in that window by 30.
def completion_rate(days, end, window=30):
start = end - timedelta(days=window - 1)
done = sum(start <= day <= end for day in days)
return done / windowA rate of 0.8 means 80 percent of the window's days were completed.
Saving and Loading Your Data
JSON stores dates as strings, so convert dates to ISO 8601 strings when saving and back to date objects when loading.
import json
from pathlib import Path
def save(log, path="habits.json"):
data = {
name: sorted(day.isoformat() for day in days)
for name, days in log.items()
}
Path(path).write_text(json.dumps(data, indent=2))
def load(path="habits.json"):
file = Path(path)
if not file.exists():
return {}
data = json.loads(file.read_text())
return {
name: {date.fromisoformat(value) for value in values}
for name, values in data.items()
}Exercise
Why should check-ins use a set instead of a list?
Show answer
A set stores each date once, so duplicate check-ins do not inflate streaks or completion rates.