cswork / libraryOpen practice workspace

Coding questions · Upstart

Calculate User Revenue and Session Duration in Python

This question evaluates proficiency in data manipulation and time-series event processing in Python, focusing on per-user revenue aggregation and sessionization to compute average session duration.

events

+---------+------------+---------+---------------------+
| user_id | event_type | revenue | timestamp           |
+---------+------------+---------+---------------------+
| 101     | view       | 0.00    | 2023-01-01 10:00:00 |
| 101     | purchase   | 29.99   | 2023-01-01 10:05:12 |
| 202     | view       | 0.00    | 2023-01-01 11:20:33 |
| 202     | purchase   | 15.50   | 2023-01-01 11:22:10 |
| 202     | logout     | 0.00    | 2023-01-01 11:30:45 |
+---------+------------+---------+---------------------+
Scenario

An e-commerce company stores clickstream events in a Python list of JSON objects; analysts need per-user revenue and average session duration for reporting.

Question

Write a Python function that takes a list of dictionaries each with keys ['user_id', 'event_type', 'revenue', 'timestamp'] and returns, for every user, total_revenue and average_session_duration (in seconds). Explain complexity.

Hints

Use one pass with defaultdict. A session starts with the first event and ends with the last for that user; avoid multiple sorts.

Per-user revenue and session duration

For each user in the events table, compute total_revenue (sum of revenue) and average_session_duration in seconds, where a session is defined as the time from the user’s first event to their last event.

Table events

columntypeconstraints
user_idINTEGER
event_typeVARCHAR(20)
revenueDECIMAL(10,2)
timestampTIMESTAMP

Sample data:

event_typerevenuetimestampuser_id
view02023-01-01 10:00:00101
purchase29.992023-01-01 10:05:12101
view02023-01-01 11:20:33202
purchase15.52023-01-01 11:22:10202
logout02023-01-01 11:30:45202

Expected output

One row per user with the sum of revenue (total_revenue) and the session duration in seconds computed as MAX(timestamp) - MIN(timestamp). With the provided data, each user has a single session, so the average_session_duration equals that session’s duration.

average_session_durationtotal_revenueuser_id
31229.99101
61215.5202

Hints

  1. Group rows by user_id to aggregate all events per user.
  2. Compute session duration as the difference between MAX(timestamp) and MIN(timestamp) per user, then convert that interval to seconds.