Sessionise user events
Problem
Events are (user_id, timestamp_seconds) in arbitrary order. For each user, a new session starts when the gap between consecutive events (after sorting by time) is strictly greater than gap. Return {user: number_of_sessions}; users without events are absent.
Signature
def count_sessions(events: list[tuple[str, int]], gap: int) -> dict[str, int]: ...Examples
The visible tests, as an interactive Python session would show them: each call and the value it should give.
>>> count_sessions([('a',0),('a',10),('a',100)], 30) == {'a': 2}
True
>>> count_sessions([('a',100),('a',0),('a',10)], 30) == {'a': 2}
TrueHints
Group events per user first — the input is not sorted.
Sort timestamps per user, then count gaps strictly greater than gap.
Duplicate timestamps produce a gap of 0 — that is not a new session.
Reference solution
from collections import defaultdict
def count_sessions(events, gap):
by_user = defaultdict(list)
for u, t in events:
by_user[u].append(t)
out = {}
for u, ts in by_user.items():
ts.sort()
n = 1
for a, b in zip(ts, ts[1:]):
if b - a > gap:
n += 1
out[u] = n
return outWhat a strong solution covers
- Groups by user, then sorts timestamps per user (O(n log n)).
- Uses the strict inequality as specified, and handles duplicate timestamps.
- Follow-up: streaming version with per-user last-seen state.
Common mistakes
- assuming input is pre-sorted
- using
>=instead of>.