48t-tests, p-values and many tests
48 t-tests, p-values and many tests
A Netflix data science candidate had to compute a t-statistic in the statistics round (1 report), and an OpenAI
round asked how you would explain a p-value (1 report). This is practice in that shape, not a leaked question. Use
only the standard library: statistics.mean and statistics.stdev (which divides by n - 1) are allowed.
Set a 45-minute timer. Read one level at a time, and run only that level's tests until they pass:
pytest problems/48_t_tests -k level1. Earlier levels must keep passing.
Level 1. t statistics. one_sample_t(xs, mu0) returns the t statistic for the mean of xs against mu0,
(mean - mu0) / (s / √n), and its degrees of freedom, n - 1. welch_t(xs, ys) returns Welch's t for
mean(xs) - mean(ys), where each group keeps its own variance, and the Welch-Satterthwaite degrees of freedom:
(vx + vy)² / (vx² / (nx - 1) + vy² / (ny - 1)), with vx = sx² / nx and vy = sy² / ny.
Level 2. Pairs and p-values. paired_t(xs, ys) tests the differences xs[i] - ys[i] against 0 and returns t and
its degrees of freedom. t_p_value(t, df) returns the two-sided p-value from Student's t curve: the area beyond -|t|
and +|t|. The density is c × (1 + x²/df)^(-(df + 1)/2), where c = Γ((df + 1)/2) / (Γ(df/2) × √(df π)), and
math.lgamma gives log Γ. Integrate it numerically, to within 1e-4.
Level 3. Permutations and many tests. permutation_p(xs, ys, reps, seed) shuffles the pooled values reps
times with random.Random(seed), splits them back into groups of the original sizes, and counts a hit when the gap
in means is at least the real gap. A gap is the absolute difference, |mean(xs) - mean(ys)|, so the test is two-sided
and the order of the groups doesn't matter. Return (hits + 1) / (reps + 1), so it's never 0. bonferroni(ps, alpha),
holm(ps, alpha) and benjamini_hochberg(ps, q) return the sorted indices of the p-values each method rejects. Bonferroni rejects each p that is at most alpha / m,
where m is the number of p-values. In all three methods a p equal to its cutoff is rejected.
Holm rejects the k-th smallest p if it is at most alpha / (m - k + 1), counting k from 1, and stops at its first
miss. Benjamini-Hochberg finds the
largest rank k whose p is at most k / m × q and rejects the k smallest.
Things to get right: n - 1 in both the standard deviation and the degrees of freedom, each group's own variance in Welch's test, both tails, and the difference between stopping at the first miss (Holm) and taking the largest rank that passes (Benjamini-Hochberg). Follow-ups from the lesson: what a p-value isn't, and why pairs beat two groups.