cswork / libraryOpen practice workspace

Coding questions · Upstart

Calculate Average Event Value by User ID

This question evaluates a candidate's skill in group-wise aggregation and data transformation on JSON-like event streams, specifically computing per-user average metrics and producing ranked results.

events

+----+---------+------------+-------+---------------------+
| id | user_id | event_type | value | timestamp           |
+----+---------+------------+-------+---------------------+
| 1  | 42      | click      | 3.5   | 2024-03-10 10:00:00 |
| 2  | 17      | view       | 1.0   | 2024-03-10 10:01:05 |
| 3  | 42      | purchase   | 7.0   | 2024-03-10 10:02:30 |
| 4  | 99      | click      | 2.3   | 2024-03-10 10:04:11 |
| 5  | 17      | purchase   | 4.7   | 2024-03-10 10:05:45 |
+----+---------+------------+-------+---------------------+
Scenario

You receive an API response that is a Python list of JSON objects, each describing a user event coming from a mobile-app funnel.

Question

Write Python code that, given a list like events = [{"id":1,"user_id":42,"event_type":"click","value":3.5,"timestamp":"2024-03-10 10:00:00"}, ...], produces a dictionary mapping each user_id to the average value of their events. Return the result sorted by descending average value.

Hints

Use defaultdict / pandas groupby; iterate only once if possible.

Average Event Value per User

Given the events table, write a SQL query to calculate the average value per user_id and return one row per user. The result should be sorted by the average value in descending order.

Table events

columntypeconstraints
idINTEGERPRIMARY KEY, NOT NULL
user_idINTEGERNOT NULL
event_typeVARCHAR(20)NOT NULL
valueDECIMAL(10,2)NOT NULL
timestampTIMESTAMPNOT NULL

Sample data:

event_typeidtimestampuser_idvalue
click12024-03-10 10:00:00423.5
view22024-03-10 10:01:05171
purchase32024-03-10 10:02:30427
click42024-03-10 10:04:11992.3
purchase52024-03-10 10:05:45174.7

Expected output

One row per user_id with the arithmetic mean of the value column across that user's events, sorted by avg_value in descending order.

avg_valueuser_id
5.2542
2.8517
2.399

Hints

  1. Use AVG(value) with GROUP BY user_id.
  2. ORDER BY the computed average in descending order.
  3. CAST the average to a fixed precision if you need two decimal places.