Count user sessions
Task
Each event is [user, ts], with ts in seconds; events are not sorted. A new session starts when more than 1,800 seconds (30 minutes) have passed since the same user's previous event; a gap of exactly 1,800 stays in the same session. Write count_sessions(events) returning {user: number of sessions}.
Python 3.14 running in your browser (Pyodide). Standard library only. print() output is shown below the results.
Tests
| Call | Expected |
|---|---|
count_sessions([['a', 0], ['a', 1000], ['a', 4000], ['b', 10]]) | {'a': 2, 'b': 1} |
count_sessions([['a', 4000], ['a', 0], ['a', 1000]]) | {'a': 2} |
count_sessions([['a', 0], ['a', 1800], ['a', 3601]]) | {'a': 2} |
count_sessions([]) | {} |
- Sort by user and time first; otherwise gaps are measured between the wrong events.
- Compare with
>, not>=: exactly 30 minutes is still the same session.
Show solution
def count_sessions(events, gap=1800):
sessions, last = {}, {}
for user, ts in sorted(events, key=lambda e: (e[0], e[1])):
if user not in last or ts - last[user] > gap:
sessions[user] = sessions.get(user, 0) + 1
last[user] = ts
return sessionsSessionisation is a gaps-and-islands problem: sort, compare each event with the previous one for the same user, and start a new session when the gap exceeds the threshold. Late or replayed events make sorting essential.
Why this works
Sessionisation is a gaps-and-islands problem: sort, compare each event with the previous one for the same user, and start a new session when the gap exceeds the threshold. Late or replayed events make sorting essential.
Revise in the Python for Data Engineers guide, or test yourself with the Python practice sets.