Metrics and Experiment Code
Original Python coding interviews on experimental units, metric denominators, observation windows, uncertainty, exact reassignment calculations, and explicit decision rules.
These problems are original practice. They are not questions from a named employer or a live hiring loop.
1.Keep assigned units in a supplied zero-fill metric
Write
assigned_metric(assignments, outcomes). assignments is[unique_string_id,string_arm]rows; outcomes maps ids to finite numbers orNone. Per arm return[assigned_count,observed_count,sum,mean], dividing byassigned_count. Under this supplied rule absent/Noneoutcomes contribute zero but are not observed. Ignore unassigned outcomes; actual zero is observed. Empty assignments returns {}.2.Quarantine arm conflicts and retain earliest assignment
Write
assignment_audit(rows),[string_id,string_arm,integer_time]observations. For each id, repeated same-arm observations are valid; retain its earliest time. If an id ever appears in multiple arms, exclude it permanently. Return{"accepted": [[id,arm,earliest_time],...],"conflicts": ids}, both in first-id-appearance order. A later repeat must not erase an arm conflict.3.Compute an allocation discrepancy statistic
Write
allocation_stat(observed, weights). observed is a nonempty list of nonnegative integer arm counts; weights is an equally long list of positive finite allocation weights. Let N=sum(observed), E_i=N*weight_i/sum(weights). Return sum((observed_i-E_i)^2/E_i), orNoneif N=0. Weights need not sum to one. Return the statistic only; do not calculate a p-value.4.Separate absolute lift relative lift and standardized excess
Write
impact_summary(control, treatment). Each argument is[successes,total]integers with 0<=successes<=total. If either total is zero returnNone. Let c and t be the arm rates. Return {"difference":t-c,"relative":(t-c)/c orNonewhen c=0,"excess":treatment_successes-treatment_total*c}. Use each arm's own denominator; do not round.5.Report a weighted contrast and usable target mass
Write
stratum_contrast(strata, weights). strata maps names to{"c":[sum,count],"t":[sum,count]}, with finite sums/nonnegative counts; weights supplies nonnegative finite weights. Use only positive-weight strata present with both counts>0. Return {"used": sorted names,"difference": normalized weighted mean oft_mean-c_meanorNone,"coverage":usable_weight/total_weightor 0 iftotal_weight=0}.6.Give each observed cluster one vote
Write
equal_cluster_mean(clusters), a dict mapping cluster names to finite numeric lists. Ignore empty lists. Return {"clusters": number of nonempty clusters,"mean": arithmetic mean of their individual means}, or meanNonewhen none qualify. Weight nonempty clusters equally regardless of row count; do not pool all rows into one mean. Do not mutate inputs.7.Compute a four-cell difference in differences
Write
difference_in_differences(rows),[arm,period,finite_value]observations with arm"C"/"T"and period"pre"/"post". Average observations separately in each of the four cells. Return (T_post-T_pre)-(C_post-C_pre), orNoneif any cell is absent. Cell sizes may differ. This function computes the supplied contrast without making a causal-identification claim.8.Average complete block contrasts rather than pooled rows
Write
block_contrasts(rows),[string_block,arm,finite_value]observations with arm"C"/"T". In blocks containing both arms compute T_mean-C_mean. Return {"blocks":[block,difference]rows sorted by block,"dropped": sorted incomplete blocks,"mean": equal-weight mean of complete block differences orNone}. An incomplete block contributes no contrast, even if it has many rows.9.Count distinct converters inside assignment windows
Write
window_conversions(assignments, events, delay, width). assignments is[unique_string_id,integer_start]rows; events is[id,integer_time]rows. delay is a nonnegative integer and width a positive integer. A user converts if any matching event satisfies start+delay<=time<start+delay+width. Return {"assigned": count,"converted": ids in assignment order,"rate": fraction orNoneif empty}.10.Exclude immature users from an exact-day retention metric
Write
mature_retention(users, events, day, as_of). users is[unique_string_id,integer_join_day]rows; events is[id,integer_day]rows. day is a nonnegative integer. Eligible users satisfyjoin_day+day<=as_of. Retained means at least one event exactly on that target day. Return{"eligible": ids,"retained": ids,"rate": retained/eligible or None}, preserving user order. Ignore duplicate events.11.Reconstruct strictly ordered event funnel completions
Write
ordered_funnel(events, stages). events is[string_id,string_stage,integer_time]rows; stages is a nonempty unique ordered string list. Per id, choose the earliest matching event for each successive stage strictly after the previous chosen time. Stop at the first missing stage. Return {"counts":[stage,users_reaching_it]rows,"complete": fully completing ids in first-id-appearance order}.12.Apply a supplied per-arm planning formula with ceilings
Write
planning_counts(variance, effect, za, zb, current, daily). variance, za and zb are nonnegative finite numbers; effect>0; current is nonnegative integer and daily positive integer. Compute target=ceil(2*variance*(za+zb)^2/effect^2), additional=max(0,target-current), days=ceil(additional/daily). Return{"per_arm":target,"additional":additional,"days":days}. This is a supplied planning formula.13.Calculate uncertainty from matched unit differences
Write
paired_summary(rows),[control_value,treatment_value]finite numeric pairs. If fewer than two pairs returnNone. Letd_i=treatment_i-control_i, m=mean(d), s2=sum((d_i-m)^2)/(n-1). Return{"difference":m,"se":sqrt(s2/n)}. Pair identities matter; do not estimate variance from separate arm lists or use population variance.14.Keep unequal-variance arm uncertainty separate
Write
unpaired_summary(control, treatment), finite numeric lists. If either has fewer than two values returnNone. Compute each sample variance with divisor n-1. Return{"difference":mean(treatment)-mean(control),"se":sqrt(s2_t/n_t+s2_c/n_c)}. Do not pool variances or assume equal sample sizes. Return only this summary, not a p-value.15.Resample whole clusters with supplied draw indices
Write
cluster_resamples(clusters, draws). clusters is a list of nonempty finite numeric lists; each draw is a list of valid cluster indices, possibly repeated or empty. For each draw concatenate all rows from those clusters, counting repeated clusters fully, and return their pooled row mean. Empty draws returnNone. Use supplied draws; do not generate randomness or average cluster means equally.16.Enumerate a two-sided fixed-size reassignment tail
Write
permutation_tail(control, treatment), nonempty integer lists with combined length<=10. Enumerate every choice ofn_toriginal positions as treatment, leaving the rest control. Count assignments whose absolute mean difference is >= the observed absolute difference, including ties. Return{"extreme":count,"total":assignments,"p":count/total}. Repeated values remain distinct positions.17.Enumerate all paired sign assignments including zero pairs
Write
sign_flip_tail(differences), integer paired differences with length<=12. For nonempty input enumerate all 2^n independent sign choices, each -1 or +1. Count signed sums with absolute value >= abs(sum(original differences)), including ties. Zero differences still have two sign choices. Return{"extreme":count,"total":2^n,"p":count/2^n}, orNonefor empty input.18.Stop a Holm step-down scan at its first failure
Write
holm_rejections(tests, alpha). tests is[unique_string_name,p_value]rows with p and alpha in[0,1]. Interpret numbers as exact decimals. Sort by p, then name; at zero-based rank i reject while p<=alpha/(m-i), stopping at the first failure. Return rejected names in original input order. Do not resume at a later larger threshold. Empty tests returns [].19.Allocate a fixed comparison budget by supplied weights
Write
weighted_rejections(tests, alpha). tests is[unique_string_name,p_value,weight]rows, p and alpha in[0,1], weight>=0. Interpret supplied numbers as exact decimals. Let W=sum(weights). Reject positive-weight tests with p<=alpha*weight/W; zero-weight tests never reject, even at p=0. Return names in input order. Return [] if W=0. Do not redistribute weight after a rejection.20.Find the first crossing of a supplied look schedule
Write
first_look_crossing(pvalues, alpha), with values and alpha in[0,1]. Interpret numbers as exact decimals. At one-based look i use threshold alpha/(i*(i+1)). Return the first i withp_i<=that threshold, orNonewhen none crosses. Use this per-look amount, not cumulative spent alpha, and keep the planned index when earlier looks fail. No randomness is involved.21.Apply a frozen baseline-covariate adjustment
Write
adjust_covariates(rows, theta, mean_x). rows are[string_id,finite_y,finite_x_or_None]; theta andmean_xare supplied finite fitted constants. Return[id,y-theta*(x-mean_x)]per row in input order. ForNonex usemean_x, leaving y unchanged. Do not fit or recompute either constant from these rows, round results, or mutate input.22.Compare covariate category distributions across arms
Write
category_balance(control, treatment), nonempty lists of category strings orNone. Compute 0.5*sum(abs(p_control(category)-p_treatment(category))) over the union of categories, with each arm normalized by its own count.Noneis a real category. ReturnNoneif either list is empty. Return this total-variation distance without a p-value or rounding.23.Locate cross-arm exposure inside assigned time windows
Write
cross_arm_users(assignments, exposures). assignments maps string ids to[assigned_arm,start,end], integer start<end. exposures is[id,arm,integer_time]rows. Return sorted unique assigned ids with any exposure to a different arm during start<=time<end. Ignore exposures outside that user's window and ids not assigned. Repeated matching or conflicting exposures count once.24.Bound binary effect when outcomes are missing
Write
binary_effect_bounds(control, treatment), lists containing 0, 1 orNone. For each nonempty arm, rate bounds are[observed_ones/n,(observed_ones+missing)/n], using all assigned entries. Return {"control": bounds,"treatment": bounds,"effect":[t_lower-c_upper,t_upper-c_lower]}. ReturnNoneif either arm is empty. Do not silently exclude missing entries from denominators.25.Expose a pooled direction opposite every stratum
Write
reversal_report(rows),[unique_string_stratum,c_success,c_total,t_success,t_total]valid integer counts with positive totals. Return {"within": sorted[stratum,t_rate-c_rate]rows,"pooled":pooled_t_rate-pooled_c_rate,"reversal":Trueonly if the pooled difference is strictly opposite every within-stratum difference}. Any tied stratum prevents reversal. Empty rows returnsNone.26.Use paired numerator-denominator residuals for ratio error
Write
ratio_summary(rows), finite[numerator,nonnegative_denominator]unit pairs. ReturnNoneif n<2 or denominator sum=0. Let r=sum(a)/sum(b),residual_i=a_i-r*b_i, and s2 be residual sample variance with divisor n-1. Return{"ratio":r,"se":sqrt(s2/(n*mean(b)^2))}. Keep each unit's numerator and denominator paired; do not average row ratios.27.Apply fixed clipping limits before summarizing a metric
Write
clipped_summary(values, low, high), finite numbers with low<=high. Replace each value below low by low and each above high by high. Return {"values": transformed list,"clipped": number originally outside[low,high],"mean": transformed mean orNoneif empty}. Values exactly on either boundary are not counted as clipped. Use supplied limits without refitting and do not mutate input.28.Merge one metric version with idempotent shard identities
Write
merge_metric_shards(rows, version). Rows are[string_shard,string_version,successes,total]nonnegative integer counts. Ignore other versions first. Count each shard once; identical retries do nothing, but unequal counts for the same selected shard returnNone. Return {"numerator":sum_successes,"denominator":sum_totals,"rate": ratio orNoneif denominator=0,"shards": unique shard count}.29.Aggregate unique metric leaves through shared branches
Write
metric_tree(graph, leaves, node). graph maps internal string nodes to child lists; leaves maps other nodes to valid[successes,total]integer counts. Return summed counts/rate and sorted unique reachable"leaves", counting a shared leaf once. Empty child lists sum to zero; zero denominator gives rateNone. ReturnNonefor any reachable cycle or unknown node. Keys cannot occur in both maps.30.Require support and directional interval evidence
Write
decision_gate(metrics, rules, min_n). metrics maps names to[n,lo,hi], finite lo<=hi and integer n>=0. rules maps names to["higher"/"lower",threshold];min_n>=0. By sorted rule name: missing metric blocks as"missing"; else n<min_nas"support"; else require lo>=threshold for higher or hi<=threshold for lower, failing as"effect". Return{"pass": no blockers,"blockers":[name,reason] rows}.