Four Stats Coding Tasks: Sample Size, DiD, Bayes, Logit
Statistics & ExperimentsModel answerLast updated
Implement four small statistics routines: z-test sample size, difference-in-differences with a pre-trend check, a Bayes posterior, and top-3 features by logistic regression coefficient.
You are given four independent coding tasks in Python or R, each applying a standard statistical idea. Write a function for each and explain the conventions you chose.
Task 1: Sample size for a two-sided z-test
Inputs:
x: historical observations of a metric. Use them to estimate the standard deviationsigmaasstd(x).alpha: significance level, for example 0.05.power: target power, for example 0.8.effect_size: the smallest absolute difference in means worth detecting, Δ.
Assume a two-sided two-sample z-test with equal group sizes. Return the smallest integer per-group sample size n that detects Δ at level alpha with the requested power.
Task 2: Difference-in-differences with a pre-trend check
Inputs are three equal-length arrays and a number:
period[i]: the time of observation i. There is at least one pre period and one post period, and there may be several pre periods.group[i]: 0 for control, 1 for treatment.outcome[i]: a numeric outcome.threshold: the largest acceptable change in the treatment-minus-control gap between consecutive pre periods.
Let Ȳ(g, t) be the mean outcome of group g in period t. The estimate is
DiD = (Ȳ(1, post) − Ȳ(1, pre)) − (Ȳ(0, post) − Ȳ(0, pre)).
For the trend check, compute the gap d_t = Ȳ(1, t) − Ȳ(0, t) for each pre period, ordered by time. The check passes if max |d_t − d_(t−1)| ≤ threshold. With only one pre period the check passes automatically.
Return the DiD estimate and a boolean for the trend check.
Task 3: Bayes posterior
Given p_A = P(A), p_B_given_A = P(B | A) and p_B_given_not_A = P(B | ¬A), return P(A | B).
Task 4: Top-3 features by logistic regression coefficient
Inputs:
X: a matrix of shapenum_features × num_samples, so each row is a feature and each column an observation.y: binary labels of lengthnum_samples.feature_names: a list of lengthnum_features.
Fit a logistic regression with an intercept. Rank the features by the absolute value of their fitted coefficients, excluding the intercept. Return the names of the top 3, most important first. Break ties by feature name in ascending order.
Inputs are well-formed and numeric. Describe how your code behaves in the edge cases you consider relevant.
Hints
Hint 1
Task 1: the difference in means has variance 2σ²/n. The effect must sit (z for 1−α/2) plus (z for power) standard errors from zero. Solve for n and round up.
Hint 2
Task 2: aggregate to (group, period) cell means first. Decide explicitly which period is post, and whether the pre baseline pools all pre observations or uses one period. State that choice.
Hint 3
Task 3: the denominator is the total probability of the evidence, P(B|A)P(A) + P(B|¬A)(1−P(A)). Leaving out the second term is the classic base-rate mistake.
Hint 4
Task 4: X is features × samples, so transpose it before fitting. Prepend a column of ones for the intercept, and don't let default L2 regularization silently change the ranking.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Each task is a standard formula. What gets marked is the formula, the conventions (ddof, one- or two-sided, intercept, axis orientation) and sensible edge-case handling. State your assumptions out loud.
Task 1: Sample size
Idea. With n per group, the difference in sample means has standard error √(2σ²/n). To reject at level α (two-sided) and still have the required power at the true difference Δ, we need
Δ / √(2σ²/n) ≥ z₁₋α/₂ + z_power.
Solving for n:
n = 2σ²(z₁₋α/₂ + z_power)² / Δ², rounded up.
The probability of rejecting in the wrong tail is ignored. It is negligible and this is the standard approximation.
Details.
- Rounding down would leave the test underpowered, so use the ceiling.
- Subtract a tiny epsilon before the ceiling so floating-point noise (62.0000000001) doesn't become 63.
np.stduses ddof=0 and R'ssduses ddof=1. The task says "std(x)", so I use ddof=0 and say so.- Reject Δ ≤ 0 or σ = 0, since n is undefined or infinite.
- Complexity: O(len(x)) time, O(1) extra space.
import math
import numpy as np
from statistics import NormalDist
def min_sample_size(x, alpha, power, effect_size):
sigma = float(np.std(np.asarray(x, dtype=float)))
if effect_size <= 0 or sigma == 0:
raise ValueError("effect_size must be > 0 and x must have variance")
nd = NormalDist()
z_total = nd.inv_cdf(1 - alpha / 2) + nd.inv_cdf(power)
n = 2 * sigma**2 * z_total**2 / effect_size**2
return max(1, math.ceil(n - 1e-9))
Task 2: Difference-in-differences and pre-trend check
Idea.
- Accumulate sums and counts per (group, period).
- Take the post period to be the latest one, or accept an explicit argument. Every other period is pre.
- Each group's pre baseline is the mean of all its pre observations, pooled. If your contract uses only the last pre period, swap that in and say so.
- DiD is the treated group's change minus the control group's change.
- For the trend check, compute the gap d_t per pre period in time order. Pass if the largest absolute consecutive change is at most
threshold. With one pre period, pass.
Why it works. Subtracting the control change removes shocks that hit both groups equally. That is valid only if the gap between groups would have stayed constant without treatment. A stable gap across the pre periods is the observable evidence for that.
Edge cases. If a group has no data in a needed period, raise an error instead of skipping it. Sorting periods costs O(P log P), so the total is O(N + P log P).
from collections import defaultdict
def did_and_trend(period, group, outcome, threshold, post_period=None):
tot, cnt = defaultdict(float), defaultdict(int)
for t, g, y in zip(period, group, outcome):
tot[(g, t)] += y
cnt[(g, t)] += 1
all_periods = sorted(set(period))
post = all_periods[-1] if post_period is None else post_period
pre = [t for t in all_periods if t != post]
if not pre:
raise ValueError("need at least one pre period")
def mean(g, ts):
c = sum(cnt[(g, t)] for t in ts)
if c == 0:
raise ValueError(f"no data for group {g}, periods {ts}")
return sum(tot[(g, t)] for t in ts) / c
did = (mean(1, [post]) - mean(1, pre)) - (mean(0, [post]) - mean(0, pre))
if len(pre) == 1:
return did, True
gaps = [mean(1, [t]) - mean(0, [t]) for t in pre]
worst = max(abs(b - a) for a, b in zip(gaps, gaps[1:]))
return did, worst <= threshold
Task 3: Bayes posterior
Idea. Use the law of total probability for the evidence:
P(A|B) = P(B|A)P(A) / [P(B|A)P(A) + P(B|¬A)(1 − P(A))].
Common mistake. Dividing by P(B|A) alone, or forgetting the false-positive term. That is the base-rate fallacy. For example, a 1% prevalence with 95% sensitivity and a 5% false-positive rate gives a posterior of about 16%, not 95%.
Edge cases. Reject probabilities outside [0, 1]. If P(B) = 0 the posterior is undefined, so raise an error (or return NaN if the grader expects one). Complexity is O(1).
def posterior(p_A, p_B_given_A, p_B_given_not_A):
for p in (p_A, p_B_given_A, p_B_given_not_A):
if not 0.0 <= p <= 1.0:
raise ValueError("probabilities must lie in [0, 1]")
num = p_B_given_A * p_A
den = num + p_B_given_not_A * (1 - p_A)
if den == 0:
raise ValueError("P(B) is zero; posterior undefined")
return num / den
Task 4: Top-3 logistic regression features
Idea.
- Transpose X. It arrives as features × samples, and fitting on the wrong axis is the most common bug.
- Prepend a column of ones for the intercept.
- Fit by maximum likelihood with Newton–Raphson (IRLS). The log-likelihood is concave, so this converges quickly. Gradient is Dᵀ(y − p), Hessian is DᵀWD with W = diag(p(1 − p)).
- Rank by |coefficient|, excluding the intercept. Sort on (−rounded |β|, name) so ties are deterministic.
Regularization. The task says "fit a logistic regression" and mentions no penalty. Scikit-learn's default applies L2 with C=1, which shrinks coefficients and can reorder them. Either pass penalty=None or use a tiny ridge on the feature coefficients only. A tiny ridge keeps the Hessian invertible and stops coefficients diverging under perfect separation.
Talking point. Raw coefficients depend on feature scale. Standardizing first gives a fairer importance ranking. The task asks for raw coefficients, so mention standardization without applying it.
Complexity. O(k(n·d² + d³)) for k Newton iterations, n samples and d features.
import numpy as np
def top3_features(X, y, feature_names):
A = np.asarray(X, dtype=float).T # samples x features
n, d = A.shape
D = np.column_stack([np.ones(n), A])
y = np.asarray(y, dtype=float)
ridge = np.diag([0.0] + [1e-8] * d) # no penalty on intercept
beta = np.zeros(d + 1)
for _ in range(100):
p = 1 / (1 + np.exp(-np.clip(D @ beta, -30, 30)))
grad = D.T @ (y - p) - ridge @ beta
w = p * (1 - p)
H = D.T @ (D * w[:, None]) + ridge
step = np.linalg.solve(H, grad)
beta += step
if np.max(np.abs(step)) < 1e-10:
break
mag = np.abs(beta[1:])
order = sorted(range(d), key=lambda i: (-round(mag[i], 12), feature_names[i]))
return [feature_names[i] for i in order[:3]]
Common mistakes across the set
- Rounding the sample size down or to nearest instead of up.
- Mixing ddof conventions without saying which one you used.
- Choosing the post period or pre baseline silently.
- Dropping the denominator's second term in Bayes' rule.
- Fitting on the untransposed matrix, including the intercept in the ranking, or using default L2 regularization without noting it.