Calculate Welch's T-Test P-Value for Experiment Rides
Arrays & HashingAuto-graded · 15 test casesLast updated
Process user experiment assignments and ride telemetry data to calculate a Welch's two-sample t-test p-value under strict filtering rules.
You are tasked with evaluating an A/B test for a new dispatch routing algorithm designed to reduce wait times (time to pickup) for riders.
Given a list of user variant assignments (users) and a list of ride events (rides), write a function welch_t_test_ttp_p_value(users, rides) to process the data and compute the two-sided Welch's t-test p-value comparing the treatment and control groups' pickup times.
Data Cleaning and Filtering Rules
-
User Assignment:
- Each dictionary in
userscontainsuser_idandvariant("treatment"or"control"). - Rides belonging to users without a valid assignment in
usersmust be ignored.
- Each dictionary in
-
Ride Filtering:
- City Filter: Keep only rides where
cityis exactly"San Francisco". - Date Filter: Keep only rides where
ride_datefalls in July 2024 (inclusive of2024-07-01up to but not including2024-08-01). Theride_datevalue can be a string formatted as"YYYY-MM-DD...", adatetime.date, or adatetime.datetimeobject. - Value Cleaning: Ignore rides where
time_to_pickupisNoneor not a finite number (NaNor infinite). Convert valid numeric values to standard floats.
- City Filter: Keep only rides where
-
Welch's Two-Sample T-Test:
- Let $a$ be the sequence of pickup times for the
treatmentgroup and $b$ for thecontrolgroup. - If either group has fewer than 2 valid data points ($\text{len}(a) < 2$ or $\text{len}(b) < 2$), return
1.0. - Calculate group sample means ($\bar{x}_a, \bar{x}_b$) and sample variances ($s_a^2, s_b^2$) with sample size $N_a - 1$ and $N_b - 1$ degrees of freedom.
- Compute standard error squared: $SE^2 = \frac{s_a^2}{N_a} + \frac{s_b^2}{N_b}$.
- If $SE^2 == 0$: return
1.0if $\bar{x}_a == \bar{x}_b$, otherwise0.0. - The t-statistic magnitude is $t = \frac{|\bar{x}_a - \bar{x}_b|}{\sqrt{SE^2}}$.
- The Welch-Satterthwaite degrees of freedom $\nu$ is: $$\nu = \frac{(SE^2)^2}{\frac{(s_a^2 / N_a)^2}{N_a - 1} + \frac{(s_b^2 / N_b)^2}{N_b - 1}}$$
- Return the two-tailed p-value corresponding to $t$ and $\nu$.
- Let $a$ be the sequence of pickup times for the
Constraints
- $0 \le \text{len}(users) \le 10,000$
- $0 \le \text{len}(rides) \le 50,000$
- Floating point results should be computed using standard double-precision arithmetic.
Examples
Example 1
Input: welch_t_test_ttp_p_value([], [])
Output: 1
Example 2
Input: welch_t_test_ttp_p_value([{'user_id': 'u1', 'variant': 'control'}, {'user_id': 'u2', 'variant': 'control'}, {'user_id': 'u3', 'variant': 'treatment'}, {'user_id': 'u4', 'variant': 'treatment'}], [{'ride_id': 'r1', 'user_id': 'u1', 'ride_date': '2024-07-03', 'city': 'San Francisco', 'time_to_pickup': 8}, {'ride_id': 'r2', 'user_id': 'u2', 'ride_date': '2024-07-05', 'city': 'San Francisco', 'time_to_pickup': 10}, {'ride_id': 'r3', 'user_id': 'u3', 'ride_date': '2024-07-04', 'city': 'San Francisco', 'time_to_pickup': 5}, {'ride_id': 'r4', 'user_id': 'u4', 'ride_date': '2024-07-06', 'city': 'San Francisco', 'time_to_pickup': 7}])
Output: 0.16794970566215622
Hints
Hint 1
Map each user_id to their respective variant first so ride filtering can quickly check user eligibility.
Hint 2
Be careful when parsing dates: handle string dates, datetime.date, and datetime.datetime objects safely.
Hint 3
Remember that sample variance divides by (n - 1). Check edge cases where variances or standard errors equal zero.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
To calculate the p-value for the routing experiment:
-
Filtering & Cleaning:
- Map each
user_idto their designatedvariant. - Iterate through
rides, discarding non-San Francisco rides, rides outside of July 2024 (2024-07-01through2024-07-31), and missing or invalid pickup times. - Separate the valid metric observations into
treatmentandcontrolarrays.
- Map each
-
Welch's T-Test Calculation:
- Verify both groups have at least 2 samples; return
1.0if not. - Compute sample means ($\bar{x}_a, \bar{x}_b$) and sample variances ($s_a^2, s_b^2$) using $N - 1$ degrees of freedom.
- Calculate standard error square: $SE^2 = \frac{s_a^2}{N_a} + \frac{s_b^2}{N_b}$.
- Determine Welch-Satterthwaite degrees of freedom $\nu$.
- Calculate two-tailed p-value using the regularized incomplete beta function $I_x(a, b)$ evaluated at $x = \frac{\nu}{\nu + t^2}$.
- Verify both groups have at least 2 samples; return
Complexity
- Time Complexity: $\mathcal{O}(U + R)$ where $U$ is the number of user records and $R$ is the number of ride records.
- Space Complexity: $\mathcal{O}(U + R)$ to store user assignments and extracted metric arrays.
import math
from datetime import date, datetime
from typing import Dict, List
def _regularized_beta(x, a, b):
if x <= 0.0:
return 0.0
if x >= 1.0:
return 1.0
def cf(a, b, x):
qab, qap, qam = a + b, a + 1.0, a - 1.0
c, d = 1.0, 1.0 - qab * x / qap
if abs(d) < 1e-300:
d = 1e-300
d = 1.0 / d
h = d
for m in range(1, 201):
m2 = 2 * m
aa = m * (b - m) * x / ((qam + m2) * (a + m2))
d = 1.0 + aa * d
if abs(d) < 1e-300:
d = 1e-300
c = 1.0 + aa / c
if abs(c) < 1e-300:
c = 1e-300
d = 1.0 / d
h *= d * c
aa = -(a + m) * (qab + m) * x / ((a + m2) * (qap + m2))
d = 1.0 + aa * d
if abs(d) < 1e-300:
d = 1e-300
c = 1.0 + aa / c
if abs(c) < 1e-300:
c = 1e-300
d = 1.0 / d
delta = d * c
h *= delta
if abs(delta - 1.0) < 3e-14:
break
return h
front = math.exp(math.lgamma(a + b) - math.lgamma(a) - math.lgamma(b) + a * math.log(x) + b * math.log1p(-x))
if x < (a + 1.0) / (a + b + 2.0):
return front * cf(a, b, x) / a
return 1.0 - front * cf(b, a, 1.0 - x) / b
def welch_t_test_ttp_p_value(users: List[Dict], rides: List[Dict]) -> float:
assignment = {row['user_id']: row['variant'] for row in users}
groups = {'treatment': [], 'control': []}
for ride in rides:
if ride.get('city') != 'San Francisco':
continue
raw_date = ride.get('ride_date')
if isinstance(raw_date, datetime):
d = raw_date.date()
elif isinstance(raw_date, date):
d = raw_date
else:
d = date.fromisoformat(str(raw_date)[:10])
if not (date(2024, 7, 1) <= d < date(2024, 8, 1)):
continue
variant = assignment.get(ride.get('user_id'))
value = ride.get('time_to_pickup')
if variant not in groups or value is None:
continue
value = float(value)
if math.isfinite(value):
groups[variant].append(value)
a, b = groups['treatment'], groups['control']
if len(a) < 2 or len(b) < 2:
return 1.0
ma, mb = sum(a) / len(a), sum(b) / len(b)
va = sum((x - ma) ** 2 for x in a) / (len(a) - 1)
vb = sum((x - mb) ** 2 for x in b) / (len(b) - 1)
xa, xb = va / len(a), vb / len(b)
se2 = xa + xb
if se2 == 0.0:
return 1.0 if ma == mb else 0.0
t = abs(ma - mb) / math.sqrt(se2)
df = se2 * se2 / (xa * xa / (len(a) - 1) + xb * xb / (len(b) - 1))
return _regularized_beta(df / (df + t * t), df / 2.0, 0.5)