Common DS Coding Question Patterns
Explore common patterns in data science coding questions involving event metrics, data reshaping, statistical calculations, and simulations. Understand how to define problem grain, validate assumptions, and implement correct solutions using Python and pandas. This lesson helps you approach coding prompts methodically, ensuring accurate interpretation and reliable results.
Coding problems involving D7 retention, calculating a median without pandas, and estimating probabilities through simulation may appear unrelated. However, these problems follow recognizable problem patterns that help identify the required intermediate results, appropriate calculations, and potential sources of error.
Consider three representative prompts:
Compute
D7retention for each signup cohort fromuser_id,event_time, andevent_name.Convert a wide monthly sales table into region-level monthly totals.
Estimate the probability that at least one of ten trials succeeds when each trial has probability 0.1.
The first prompt is an event metric. We need a user-level signup table before we can count a cohort. The second is a transformation pipeline. We need to preserve the table’s grain while reshaping and aggregating. The third is a small simulation. We need one random draw per trial and one boolean result per simulated run.
A fourth common shape asks us to implement a familiar statistic from primitives. A prompt such as “write a median function without a library” tests whether we make edge-case policies explicit, especially for sorted inputs, even-length inputs, and missing values.
The fastest reliable start is to label the shape, state the output grain, and name one invariant to inspect. For the retention prompt, the first intermediate table is one row per user_id with a signup_date. For the reshaping prompt, the first check is whether the output still has one row per region and month. For the simulation prompt, the first check is whether each simulated run contains exactly ten independent Bernoulli trials.
Retention from raw events
For an event metric, staged tables make the denominator visible before aggregation hides it. Suppose an interviewer asks us to compute D7 retention for users who signed up on each calendar date.
A defensible cohort definition is narrower. A user belongs to the cohort determined by the date of that user’s signup event. An eligible user has reached the seventh day after signup within the observed event window. A retained user generated at least one qualifying event on day seven. The result has one row per cohort_date, not one row per event.
The code builds those stages from a small events table and prints the cohort summary. Check that retained_users never exceeds eligible_users, and check that a user with multiple day-seven events still contributes only one retained user.
In the main.py ...