FreeExam

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. 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. 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. 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. Return sum(weight*sample_mean)/sum(weight), or None if total weight=0. Sample counts may differ and do not replace population weights. Do not mutate.

  4. 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) or None if n=0,"se":sqrt(sum((y-mean)^2)/(n*(n-1))) or None if n<2}. Do not treat the 2*n members as independent observations.

  5. 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 and expected_control are supplied independently; do not fit them on these rows or mutate inputs.

  6. 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 or None if empty,"normalized":sum(w*value)/sum(w) or None if zero weight}. Do not replace either denominator or mutate.

  7. 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 is None if 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. 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. 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 is product(right-left), empty bounds gives 1. Return {"estimate":volume*mean or None if no values,"se":volume*sqrt(sum((v-mean)^2)/(n*(n-1))) or None if n<2}. Do not generate draws.

  10. 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. 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 yields None. Empty draws returns []. Do not sample, sort, deduplicate or mutate.

  12. 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 between floor(h) and ceil(h). Return [quantile(low),quantile(high)], or None if empty. Interpret decimal q exactly for rank decisions; do not mutate replicates.

  13. 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. Return mean(after-before) per indexed resample, or None for an empty replicate. Repeated indices repeat the entire pair. Do not resample the two measurements independently or mutate inputs.

  14. 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 return None. Otherwise compute each leave-one-out ratio r[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. 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 whose abs(signed_sum)>=observed. Return {"extreme":count,"total":2^n,"p":count/total}. Empty input has one assignment.

  16. 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. 17.Retain add-one support in a sampled randomization tail

    Write sampled_tail(observed, randomized). Finite scalars. Count b values in randomized satisfying abs(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. 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. 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. 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 find abs(pi[i]*P[i][j]-pi[j]*P[j][i]). Return {"gap":largest gap,"pair":[i,j]}, ties lexicographically; pair=None if all gaps are zero. Compare exactly and do not mutate.

  21. 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 or None,"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. 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 in range(n-k))/(n-k). Return None for k>=n, including empty values. Do not refit separate overlap means or divide every lag by n.

  23. 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. 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) or None if K=0,"se":sqrt(sum((y-mean)^2)/(K*(K-1))) or None if K<2}. Treat batches as supplied independent units.

  25. 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. 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. 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. 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, set base[i]=floor(count*p[i]), R=count-sum(base). uniforms has R values in [0,1). Output each index base[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. 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; replace reservoir[draw] with this item iff draw<capacity. Return {"reservoir":final_items,"history":copies after every arrival}. Do not sort or mutate.

  30. 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 or None (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 and log_evidence=None. Do not mutate.

AI Research Scientist: Statistical Simulation Code Coding Practice Questions · FreeExam