FreeExam

Statistical Estimators in Code

Thirty original Python problems on robust location, weighted sampling, tied ranks, posterior moments, correlated observations, survival summaries and constrained estimation. Implement explicit numeric contracts and test their support boundaries.

These problems are original practice. They are not questions from a named employer or a live hiring loop.

  1. 1.Invert a weighted empirical distribution

    Write mass_quantile(rows, q). rows are [value,weight] finite numbers, weights >=0; q in [0,1]. Ignore zero weights. Return the smallest supported value whose cumulative weight is >= q times total weight; q=0 returns the minimum supported value. Return None if total weight is zero. Do not interpolate or mutate inputs.

  2. 2.Report every weighted absolute-loss minimizer

    Write median_interval(rows) for finite [value,weight] rows, weight>=0. Return [lo,hi], the entire interval minimizing sum(weight*abs(value-location)). Ignore zero weights. A half-mass gap makes both endpoints and all points between them minimizers. Return None for zero total weight. No mutation.

  3. 3.Distinguish reliability weights from replication

    Write reliability_moments(rows) for finite [x,w], w>=0. Set W=sum(w), Q=sum(w*w). Return [weighted_mean, corrected_variance, W*W/Q]. Variance divides sum(w*(x-mean)**2) by W-Q/W; return None for that variance if its denominator is zero. If W=0 return [None,None,None]. No mutation.

  4. 4.Compute a distinct-unit inclusion summary

    Write inclusion_summary(rows). Each row is [value, inclusion_probability] for a DIFFERENT sampled unit; values finite and 0<probability<=1. Return [sum(value/probability), sum(1/probability), ratio_of_those_sums]. Empty rows return [0,0,None]. This implements supplied inclusion weights, without validating a sampling design. No mutation.

  5. 5.Separate stratified mean and variance support

    Write strata_summary(strata): map name->[N,sample], integer N>=0, finite sample size n<=N. Return [mean,variance], mean=sum(N*sample_mean)/sum(N). Variance=sum((N/total_N)**2*(1-n/N)*s2/n), s2 uses n-1. N=0 strata ignored. Any positive-N empty sample makes both None; n=1 noncensus makes variance None. A census contributes zero variance. All N=0 returns [None,None].

  6. 6.Choose a robust location from supplied candidates

    Write huber_choice(rows, delta, candidates). Finite [x,w], w>=0, delta>0. For residual r=x-c, loss is r*r/2 if abs(r)<=delta, else delta*(abs(r)-delta/2). Return [best_candidate,total_weighted_loss], minimizing over candidates only; ties choose smaller candidate. Empty candidates return None. All-zero weights still choose the smallest candidate. No mutation.

  7. 7.Compute a median and an unscaled MAD

    Write median_mad(values) for finite numbers. Return [median, median_absolute_deviation], taking the midpoint of the two central values for every even-sized median. MAD is median(abs(x-median)); apply no consistency multiplier. Empty input returns [None,None]. No mutation.

  8. 8.Give nonempty blocks equal influence

    Write block_median(blocks). Compute each nonempty block mean, then the median of these means, using the midpoint for an even number of blocks. Return [median_of_means,number_of_nonempty_blocks]; return [None,0] if none. Blocks contain finite numbers. Do not pool all observations or weight blocks by size. No mutation.

  9. 9.Handle zeros across three weighted means

    Write three_means(rows) for finite [x,w], x>=0,w>=0. Return [arithmetic,geometric,harmonic] with weights normalized by total positive weight W. Geometric=exp(sum(w*log(x))/W), harmonic=W/sum(w/x). Ignore zero-weight rows. Any positive-weight x=0 makes geometric and harmonic zero. W=0 returns [None,None,None]. No mutation.

  10. 10.Merge centered sufficient moment summaries

    Write merge_moments(summaries). Each [n,mean,M2] has integer n>=0 and M2=sum squared deviations within that group; n=0 entries are ignored. Inputs describe valid finite groups. Return [total_n,combined_mean,sample_variance], including between-group scatter. Empty total returns [0,None,None]; total_n=1 variance is None. No mutation.

  11. 11.Expose both empirical CDF limits

    Write cdf_brackets(values, queries) for finite numbers. For each query q return [fraction_of_values_strictly_below_q,fraction_at_or_below_q], preserving query order and repetitions. An empty sample gives [None,None] for every query. Retain repeated observations as separate mass. No mutation.

  12. 12.Check both sides of empirical CDF jumps

    Write cdf_distance(probabilities). These are supplied continuous-null CDF values F(X_i), each in [0,1]. Sort them as p_i, i=1..n. Return [Dplus,Dminus,D], where Dplus=max(i/n-p_i), Dminus=max(p_i-(i-1)/n), D=max(Dplus,Dminus). Empty returns [None,None,None]. Retain repeated probabilities. Compute no p-value. No mutation.

  13. 13.Count collisions between distinct observations

    Write pair_collision(counts) for a map of category names to nonnegative integer counts. Return sum(c*(c-1))/(n*(n-1)), n=sum(counts), or None for n<2. This compares two distinct observed positions, not draws with replacement from empirical proportions. Zero-count categories contribute nothing. No mutation.

  14. 14.Apply an uncapped natural-log entropy correction

    Write corrected_entropy(counts) for nonnegative integer category counts. With n total and k positive-count categories, return [H,H+(k-1)/(2*n)], H=-sum((c/n)*ln(c/n)) over positive counts. Empty total returns [None,None]. Use natural logs; do not cap the correction at ln(k). This is a specified first-order correction, not an exact unbiasedness guarantee. No mutation.

  15. 15.Estimate unseen mass from observed singletons

    Write singleton_mass(counts) for a map of names to nonnegative integer counts. Return [number_of_singleton_categories, singleton_count/total_observations]. If total is zero return [0,None]. A singleton means count exactly one. This is only the supplied missing-mass kernel, not a full smoothed distribution or a guarantee about unseen identities. No mutation.

  16. 16.Deduplicate captures before estimating overlap

    Write capture_summary(first, second) for lists of string unit IDs. Deduplicate within each list. Let n1,n2 be distinct sizes and m the intersection size. Return [n1,n2,m,(n1+1)*(n2+1)/(m+1)-1]. Apply this supplied Chapman kernel even for zero overlap or empty lists. Sampling assumptions are not checked. No mutation.

  17. 17.Normalize histogram totals independently

    Write histogram_tv(left, right) for maps from strings to nonnegative integer counts. Normalize each histogram by its own total. Return half the sum of absolute probability differences over the union of keys. If either total is zero return None. Missing keys mean zero; declared zero-count keys add no mass. No mutation.

  18. 18.Center only complete observation pairs

    Write paired_pearson(rows) for [x,y] rows; each value is finite or None. Drop any row missing either coordinate, then return [complete_count,Pearson_correlation]. Return None correlation for fewer than two complete rows or either constant coordinate. Observed zero is not missing. No mutation.

  19. 19.Rank complete pairs with midpoint ties

    Write paired_spearman(rows) for finite-or-None [x,y] pairs. Keep complete rows BEFORE ranking each coordinate. Equal values receive the average of their occupied 1-based ranks. Return [complete_count,Pearson_correlation_of_ranks], using None correlation for fewer than two rows or a constant ranked coordinate. No mutation.

  20. 20.Keep joint ties out of one-coordinate tie counts

    Write kendall_evidence(rows) for <=80 complete finite [x,y] pairs. For every unordered pair classify concordant C, discordant D, tied-only-x Tx, tied-only-y Ty, or tied-both Txy. Return [C,D,Tx,Ty,Txy,tau], tau=(C-D)/sqrt((C+D+Tx)*(C+D+Ty)); zero denominator gives None. Identical rows still form a tied-both pair. No mutation.

  21. 21.Use the joint residual intercept for a median slope

    Write joint_line(rows) for <=60 finite [x,y] points. Form slopes (y_j-y_i)/(x_j-x_i) for every unordered pair with distinct x. Slope is their median; intercept is median(y-slope*x) over ALL points. Even medians use central midpoints. Return [slope,intercept], or [None,None] if no distinct-x pair. This explicitly uses the joint residual intercept. No mutation.

  22. 22.Keep the error-variance ratio direction explicit

    Write deming_line(rows, ratio). ratio>0 is Y-error variance / X-error variance. Center finite pairs; A=sum(dx*dx), B=sum(dy*dy), C=sum(dx*dy), z=B-ratio*A. Slope=(z+sqrt(z*z+4*ratio*C*C))/(2*C); intercept=mean_y-slope*mean_x. Return [slope,intercept]; fewer than two rows or C=0 returns [None,None]. Use a stable equivalent root when z<0. No mutation.

  23. 23.Report an interior beta mode only when it exists

    Write beta_moments(alpha,beta,successes,failures). Positive finite alpha,beta and nonnegative integer counts give a=alpha+successes, b=beta+failures. Return [a,b,a/(a+b),a*b/((a+b)**2*(a+b+1)),interior_mode]. Interior mode=(a-1)/(a+b-2) only if a>1 and b>1; otherwise None, without choosing a boundary mode.

  24. 24.Keep posterior covariance across all declared categories

    Write category_posterior(prior, counts). Maps have the same nonempty string keys; prior values positive finite, counts nonnegative integers. Sort keys. For a_i=prior_i+count_i, A=sum(a), return [sorted_keys,[a_i/A],covariance_matrix]. Diagonal=a_i*(A-a_i)/(A*A*(A+1)); off-diagonal=-a_i*a_j/(A*A*(A+1)). Retain categories with zero observations. No mutation.

  25. 25.Separate posterior rate variance from predictive variance

    Write rate_posterior(shape,rate,count,exposure,future). Use a Gamma SHAPE-RATE prior with positive shape,rate; count>=0 integer; exposure,future>=0 finite. Update a=shape+count,b=rate+exposure. Return [a,b,rate_mean,rate_variance,predictive_mean,predictive_variance], where rate moments=a/b,a/b**2 and future count moments=future*a/b, future*a/b+future**2*a/b**2.

  26. 26.Combine prior and known-noise observation precision

    Write normal_posterior(prior_mean,prior_variance,noise_variance,values). Variances positive finite, observations finite. Posterior precision P=1/prior_variance+n/noise_variance. Return [(prior_mean/prior_variance+sum(values)/noise_variance)/P,1/P]. Empty observations return the prior moments. Noise variance is known per observation, not an estimated sample variance. No mutation.

  27. 27.Apply positive-part shrinkage around a fixed target

    Write shrink_vector(values,target,variance). Equal-length finite vectors have dimension d>=3; variance>=0 is known. Let R=sum((x-t)**2), c=max(0,1-(d-2)*variance/R); define c=0 if R=0. Return [c,[t+c*(x-t)]]. Implement this supplied numeric rule without asserting that the data satisfy a distributional model. No mutation.

  28. 28.Use a full covariance matrix for an intercept estimate

    Write correlated_mean(values,covariance). 1<=n<=6 finite values; covariance is a supplied symmetric positive-definite n-by-n matrix. Solve covariance*w=ones. Return [sum(w_i*x_i)/sum(w),1/sum(w),[w_i/sum(w)]]. Negative normalized weights are allowed. Return numeric values, not fractions. No mutation. The covariance is known, not estimated here.

  29. 29.Group tied failures before removing tied censors

    Write failure_curve(rows) for [time,event] observations, finite time>=0 and boolean event. At each distinct failure time t, risk r counts all rows with time>=t; d counts failures at t. Update S*=1-d/r and H+=d/r, initially S=1,H=0. Return [t,r,d,S,H] rows in time order, ONLY at failure times. Same-time censors remain at risk for that failure step. Empty/all-censored returns []. No mutation.

  30. 30.Pool adjacent violations using observation weight

    Write monotone_fit(values,weights). Equal-length lists, n<=30; finite values, strictly positive finite weights. Return [fitted_values,weighted_squared_error], minimizing sum(w_i*(x_i-fit_i)**2) subject to nondecreasing fitted values in ORIGINAL order. Return [[],0] when empty. Do not sort the observations or mutate inputs.