Statistical Simulation Code
Original Python research interviews on reproducible sampling, variance reduction, resampling, finite randomization, chain diagnostics, and particle-weight updates.
These problems are original practice. They are not questions from a named employer or a live hiring loop.
1.Skip zero-mass categories at exact cumulative boundaries
Write
discrete_draws(weights, uniforms). weights is nonnegative finite numbers with positive sum; uniforms is finite numbers in [0,1). Interpret decimals exactly. For each u return the first zero-based index whose cumulative weight is strictly greater than u*sum(weights). Return indices in draw order. Do not generate randomness or mutate inputs.2.Invert bin mass while preserving each interval width
Write
piecewise_draws(edges, masses, uniforms). Increasing finite edges has one more entry than nonnegative finite masses, whose sum>0. Each bin is uniform within its interval. For u in [0,1), find the first cumulative mass>u*total, then linearly place the remaining mass fraction inside that bin. Use exact decimal decisions, preserve draw order, and do not mutate.3.Weight strata by population share rather than sample count
Write
stratified_mean(strata). Rows are[nonnegative_population_weight,finite_samples]. Positive-weight rows have at least one sample; zero-weight rows may be empty. Returnsum(weight*sample_mean)/sum(weight), orNoneif total weight=0. Sample counts may differ and do not replace population weights. Do not mutate.4.Measure uncertainty using independent pair means
Write
pair_summary(pairs). Each finite[a,b]is one independent simulation pair; members within a pair may be dependent. Let y=(a+b)/2. Return {"pairs":n,"mean":mean(y)orNoneif n=0,"se":sqrt(sum((y-mean)^2)/(n*(n-1))) orNoneif n<2}. Do not treat the 2*n members as independent observations.5.Apply a frozen control coefficient to fresh observations
Write
control_adjust(rows, expected_control, beta). rows is finite[value,control]pairs; other inputs finite. For each row set adjusted=value-beta*(control-expected_control). Return{"adjusted":values,"estimate":their mean or None if empty}. beta andexpected_controlare supplied independently; do not fit them on these rows or mutate inputs.6.Keep ordinary and self-normalized estimates distinct
Write
importance_estimates(rows). Each finite[value,target_density,proposal_density]has target>=0 and proposal>0. A normalized target is assumed. Set w=target/proposal. Return {"ordinary":sum(w*value)/n orNoneif empty,"normalized":sum(w*value)/sum(w)orNoneif zero weight}. Do not replace either denominator or mutate.7.Report effective support from unequal importance weights
Write
weight_support(weights). Nonnegative finite weights need not sum to one. Return{"mass":sum(weights),"ess":sum(weights)^2/sum(w^2)}; ess isNoneif every weight is zero, including empty input. Count zero-weight entries in neither mass nor effective support. Do not substitute the number of nonzero entries.8.Apply a supplied rejection envelope with strict acceptance
Write
rejection_trace(rows, envelope). Each row is[unique_id,p,q,u], finite exact decimals with q>0, 0<=p<=envelope*q and 0<=u<1; envelope>0. Accept iff u*envelope*q<p. Return{"accept":ids,"reject":ids}in input order. A zero target density is rejected even at u=0. Do not generate proposals or randomness.9.Scale the sample mean and its error by box volume
Write
integral_summary(values, bounds). values are finite function observations from supplied independent uniform box draws; bounds is finite[left,right]with left<right. Volume isproduct(right-left), empty bounds gives 1. Return {"estimate":volume*mean orNoneif no values,"se":volume*sqrt(sum((v-mean)^2)/(n*(n-1))) orNoneif n<2}. Do not generate draws.10.Retain the between-mean term when merging moment states
Write
merge_moments(left, right). Each valid state is [nonnegative_integer_count,finite_mean,nonnegative_centered_square_sum]. A zero-count state is ignored regardless of stored mean/sum. Merge into[n,mean,M2], including delta^2*n_left*n_right/n for delta=mean_right-mean_left. If both counts are zero return[0,0,0]. Do not mutate.11.Preserve repeated sample identities in supplied resamples
Write
bootstrap_means(values, draws). values is finite; draws lists index lists with valid zero-based indices into values. Return the mean of each indexed resample in draw order. Repeated indices count repeatedly; an empty index list yieldsNone. Empty draws returns []. Do not sample, sort, deduplicate or mutate.12.Interpolate bootstrap endpoints on the declared rank scale
Write
empirical_interval(replicates, low, high). replicates is finite; 0<=low<=high<=1. Sort a copy.Quantile(q)uses h=(n-1)*q, interpolating linearly betweenfloor(h)andceil(h). Return[quantile(low),quantile(high)], orNoneif empty. Interpret decimal q exactly for rank decisions; do not mutate replicates.13.Share each resampled index across both paired measurements
Write
paired_resamples(pairs, draws). pairs is finite[before,after]rows; draws contains valid index lists. Returnmean(after-before)per indexed resample, orNonefor an empty replicate. Repeated indices repeat the entire pair. Do not resample the two measurements independently or mutate inputs.14.Keep undefined leave-one-out ratios out of variance claims
Write
jackknife_ratio(rows). Finite[numerator,nonnegative_denominator]rows. If n<2 or any leave-one-out denominator sum=0 returnNone. Otherwise compute each leave-one-out ratior[i]in row order, mean rbar, and variance=(n-1)/n*sum((r[i]-rbar)^2). Return{"replicates":ratios,"variance":variance}. Do not treat replicates as independent.15.Count every bounded sign assignment in a two-sided test
Write
sign_randomization(differences). At most 12 finite exact-decimal paired differences. Enumerate every sign vector in{-1,1}^n, including multiplicity for zero differences. Observed statistic is abs(sum(differences)). Count assignments whoseabs(signed_sum)>=observed. Return{"extreme":count,"total":2^n,"p":count/total}. Empty input has one assignment.16.Enumerate assignments by sample identity rather than value
Write
label_randomization(values, size). There are 2..12 finite exact-decimal values and 1<=size<len(values). Observed group A is the first size positions. Enumerate every size-position subset as A; B is its complement. Statistic is abs(mean(A)-mean(B)). Return {"extreme":assignments with statistic>=observed,"total":assignment_count,"p":extreme/total}. Preserve duplicate identities.17.Retain add-one support in a sampled randomization tail
Write
sampled_tail(observed, randomized). Finite scalars. Count b values in randomized satisfyingabs(value)>=abs(observed). Return{"extreme":b,"draws":len(randomized),"p":(b+1)/(len(randomized)+1)}. Include ties and the supplied add-one convention. Empty randomized gives p=1; do not claim enumeration of all assignments.18.Advance a chain from its current row at each supplied draw
Write
chain_draws(matrix, initial, uniforms). matrix is a finite nonnegative square transition matrix, each exact-decimal row sums to 1; initial is a valid state index. For each u in [0,1), select the first state in the current row with cumulative probability>u, then update current state. Return initial followed by every selected state. No generated randomness or mutation.19.Check a candidate stationary distribution by incoming mass
Write
stationarity_residual(matrix, masses). matrix is an n-by-n nonnegative exact-decimal transition matrix, row sums 1, n>=1; masses are nonnegative finite length n with positive total. Normalize masses to pi. Return{"residual":pi*matrix-pi,"max_abs":largest absolute residual}. Use incoming column sums, preserve state order, and do not mutate.20.Distinguish detailed balance from stationarity alone
Write
balance_gap(matrix, masses). n>=1 transition matrix has exact-decimal nonnegative rows summing to 1; masses>=0 has positive total. Normalize masses to pi. For each i<j findabs(pi[i]*P[i][j]-pi[j]*P[j][i]). Return{"gap":largest gap,"pair":[i,j]}, ties lexicographically; pair=Noneif all gaps are zero. Compare exactly and do not mutate.21.Keep unobserved target visits separate from late visits
Write
passage_times(trajectories, targets). trajectories contains state-string lists, including the starting state at index 0 when present; targets lists strings. Return {"hits":first target index per trajectory orNone,"censored":indices of trajectories with no observed target}. An initial hit is 0; an empty trajectory is censored. Do not replace absent hits with length.22.Use the global mean but the actual lag overlap count
Write
lag_covariances(values, lags). values is finite; lags are nonnegative integers in desired order. Use the full-series mean m. For 0<=k<n return sum((values[i]-m)*(values[i+k]-m) for i inrange(n-k))/(n-k). ReturnNonefor k>=n, including empty values. Do not refit separate overlap means or divide every lag by n.23.Stop a supplied autocorrelation sum at its first bad pair
Write
positive_pair_time(rhos). Finite autocorrelations start at lag 0 (rhos[0]=1 if nonempty). Examine complete pairs (0,1),(2,3),...; stop before the first pair sum<=0, ignore any unpaired last value. Let raw=-1+2*sum(kept pair sums). Return{"pairs":kept_count,"tau":raw or None if no pair or raw<=0}. Use exact decimal comparisons. No monotone adjustment.24.Estimate uncertainty from complete batch means only
Write
batch_summary(values, size). values is finite and size>=1 integer. Split from position 0 into nonoverlapping size-element batches; drop only the incomplete tail. For K complete batch means y, return {"means":y,"estimate":mean(y)orNoneif K=0,"se":sqrt(sum((y-mean)^2)/(K*(K-1))) orNoneif K<2}. Treat batches as supplied independent units.25.Separate within-chain and between-chain variation
Write
chain_ratio(chains), M>=2 equal-length finite chains with N>=2. Let means be chain means; W=mean(sample variances using N-1), B=N*sum((mean-grand_mean)^2)/(M-1), V=(N-1)*W/N+B/N. Return{"within":W,"between":B,"variance":V,"ratio":sqrt(V/W) or None if W=0}. Do not split, rank-normalize, pool variances, or clamp ratio to 1.26.Convolve unequal independent Bernoulli probabilities
Write
bernoulli_distribution(probabilities). Exact-decimal success probabilities lie in[0,1]. Return a length n+1 list where entry k is probability of k successes from these independent trials. Start empty trials with[1]; include zero/one probabilities. Update all coefficients from the previous distribution rather than reusing newly updated entries.27.Use one offset for an evenly spaced offspring grid
Write
systematic_indices(weights, count, offset). Nonnegative exact-decimal weights have positive sum; count>=1 integer and 0<=offset<1/count. Normalize weights. For grid points offset+i/count, i=0..count-1, choose first cumulative probability strictly greater than the point. Return indices in grid order. Do not generate independent uniforms or mutate.28.Allocate deterministic offspring before residual draws
Write
residual_indices(weights, count, uniforms). Nonnegative exact-decimal weights have positive sum; count>=0 integer. Normalize to p, setbase[i]=floor(count*p[i]), R=count-sum(base). uniforms has R values in [0,1). Output each indexbase[i]times in index order, then categorical draws from residual masses count*p-base in uniform order using strict cumulative>u*R. No mutation.29.Replay supplied reservoir replacement indices by arrival
Write
reservoir_history(items, capacity, draws). items lists strings; capacity>=1 integer. Fill the reservoir from the first capacity arrivals. For each later zero-based arrival i, the corresponding supplied draw is an integer 0..i; replacereservoir[draw]with this item iff draw<capacity. Return{"reservoir":final_items,"history":copies after every arrival}. Do not sort or mutate.30.Normalize particle evidence without exponentiating raw logs
Write
particle_update(priors, log_likelihoods). Equal-length lists; nonnegative finite priors sum to 1 unless empty. Log likelihoods are finite orNone(zero likelihood). Return {"weights":normalized prior*likelihood,"log_evidence":log(total unnormalized weight)} using stable log arithmetic. Zero priors stay zero. If all support is zero return zero weights andlog_evidence=None. Do not mutate.