Experiment and Error Analysis Code
Original Python applied AI interviews on failure transitions, judge consistency, reproducible traces, perturbation evidence, finite attribution, model cascades, and error-distribution diagnostics.
These problems are original practice. They are not questions from a named employer or a live hiring loop.
1.Keep abstention and missing states in run transitions
Write
outcome_transitions(gold, before, after). gold maps ids to string labels; predictions map ids to string labels orNone. States in order:"correct","wrong","abstain"(presentNone),"missing"(absent). Return {"states":that order,"counts":4x4 old-state/new-state counts over gold ids,"extra":sorted prediction ids outside gold from either run}. Empty-string labels are observed. No mutation.2.Prioritize harmful changes with exact severity ties
Write
regression_queue(rows, gap). Rows[unique_id,old_loss_or_None,new_loss_or_None,severity>=0]; gap>=0, finite exact decimals. Missing either loss is unsupported. Keep supported rows with delta=new-old>gap, even severity 0. Return {"queue":[id,delta,severity*delta]sorted by descending priority, descending delta, then id,"unsupported":sorted unsupported ids}. Do not mutate.3.Roll distinct failing identities through an error taxonomy
Write
taxonomy_rollup(parents, rows). parents maps each known error label to a parent label orNoneand is acyclic. rows are[unique_example_id,known_label_list]. Each example supports its tags and every ancestor once, even with overlapping or repeated tags. Return[label,sorted_example_ids]for all labels sorted by label, including empty support. Do not mutate.4.Keep both directions of each unordered confusion pair
Write
confusion_pairs(rows). Rows[gold_label,predicted_label]contain strings. Ignore correct rows. For each unordered unequal pair low<high, count gold=low/pred=high as forward and the reverse as backward. Return[low,high,forward,backward,forward-backward]sorted by (low,high). Repeated errors count separately; do not merge a pair into one undirected total or mutate.5.Find mutually reachable majority-preference components
Write
preference_components(models, votes). models lists unique names; votes are[winner,loser]with known distinct models. Add directed a->b iff votes a>b outnumber b>a; ties add neither edge. Return sorted model lists for maximal mutually reachable components, ordered by first name. Include isolated models. Reachability may use indirect paths; a one-way chain is not a component. No mutation.6.Compare normalized outcomes across reversed presentation
Write
presentation_audit(rows). Rows[item,orientation,result]have unique (item,orientation); orientation"ab"/"ba", result"left"/"right"/"tie". Normalize winners to"a"/"b"/"tie". Return[item,status,ab_winner_or_None,ba_winner_or_None]sorted by item: status"incomplete"if either orientation is absent, else"consistent"iff outcomes agree, otherwise"inconsistent". No mutation.7.Bound weighted rubric totals with missing criterion scores
Write
rubric_bounds(weights, ranges, scores, threshold), finite exact decimals. weights>=0; ranges gives[low,high]per criterion. Scores are in range; absent/Noneis missing. Sum weight*score or weight*range endpoints when missing. Return {"lower":lower,"upper":upper,"decision":"pass"if lower>=threshold,"fail"if upper<threshold, else"uncertain"}. No weight normalization or mutation.8.Audit rubric relations with unsupported fields
Write
rubric_constraints(scores, rules). scores maps names to finite decimals orNone; rules are[left,right,margin], requiringscores[right]-scores[left]>=margin. An absent/Noneendpoint is unsupported. Return{"violated":indices of supported false rules,"unsupported":unsupported indices}, each in input order. Interpret decimals exactly; equality passes and zero scores are observed. No mutation.9.Group exact error signatures after one alias lookup
Write
error_signatures(rows, aliases). Rows[unique_id,error_code_list]; aliases maps codes to replacements. Apply exactly onealiases.get(code,code), even if the result is also an alias key. Deduplicate/sort canonical codes. Return[canonical_code_list,sorted_ids]grouped by signature, ordered lexicographically by code list. Include empty signatures. No mutation.10.Compute oriented weighted edit cost between step traces
Write
trace_edit_cost(before, after, insert, delete, substitute). Traces list string step tokens; costs are integers>=0. Transform before into after using token insertion, deletion or substitution. Equal-token alignment costs 0; unequal substitution costs substitute, but delete+insert may be cheaper. Return minimum total cost. Token order and multiplicity matter; no transposition. No changes.11.Validate only a linked experiment trace prefix
Write
trace_chain(events, root). Events[sequence,parent_digest,digest]use integer sequences and opaque strings. Expect sequence 0,1,... and parent equal to root then the last valid digest. Stop at first bad event, checking sequence before parent. Return {"accepted":count,"last":last valid digest or root,"error":[index,"sequence"/"parent"]orNone}. Links only, not authentication. No changes.12.Audit the full configuration and each one-factor ablation
Write
ablation_support(factors, settings). factors lists unique names; settings hold names, possibly unknown/repeated. Expect all factors, then each leave-one-out in factors order. Canonicalize as sorted distinct names. Return {"missing":absent expected settings in their order,"duplicates":[setting,count]for counts>1 sorted by setting,"unexpected":sorted distinct other settings}. No mutation.13.Test supplied same-or-flip prediction relations with support
Write
perturbation_audit(rows). Rows [unique_id,baseline_bool_or_None,variant_bool_or_None,relation], relation"same"or"flip". Missing either output is unsupported. Otherwise pass iff outputs are equal for same, unequal for flip. Return{"passed":ids,"failed":ids,"unsupported":ids}, each in input order.Falseis observed; do not infer that the supplied relation is semantically valid or mutate.14.Locate an edit window and affected protected spans
Write
edit_scope(before, after, protected), Python strings, valid half-open source ranges. Use longest common prefix p, then longest suffix not overlapping p in either string. Return{"before":[p,old_end],"after":[p,new_end],"touched":protected indices}. Nonempty old edits touch by positive overlap; pure insertion only strictly inside a range. Identical strings touch none. No mutation.15.Find inclusion-minimal supplied failing component sets
Write
minimal_failures(failures). Each entry lists component ids of an observed failing configuration. Deduplicate entries and ids, then keep sets having no other supplied failing proper subset. Return sorted id lists ordered by (size,lexicographic ids). An empty failing set dominates every nonempty set. Do not assume unobserved configurations pass or that failures are monotone. No mutation.16.Average marginal contributions over every component ordering
Write
finite_attribution(names, values). n<=7 unique ordered names; values has 2**n finite exact decimals indexed by mask (bit i isnames[i]). For each permutation start mask 0; give each added namevalues[new]-values[old]. Return {"values":[name,mean_contribution]in names order,"total_change":values[-1]-values[0]}. Nonzero baseline allowed; n=0 yields empty attribution/change 0. No mutation.17.Measure correct-model union and unique rescue evidence
Write
oracle_support(gold, predictions). gold maps ids to string labels; predictions maps model to id->label_or_None. Return {"oracle":fraction of gold ids correct in any model, orNonefor empty gold,"unique":[model,count of gold ids correct only in that model]sorted by model,"unanswered":sorted gold ids with no non-Noneprediction in any model}. Ignore extra ids; "" is observed. No mutation.18.Replay a fixed cascade with answer support and stage costs
Write
cascade_cases(cases, thresholds). Cases[id,stages]; each stages list matches thresholds length, holding[confidence,prediction_or_None,cost>=0]. Confidences/thresholds in[0,1], exact decimals. Charge each executed stage; stop at first non-Noneprediction with confidence>=threshold. Return [id,chosen_0_based_stage_or_None,prediction_or_None,total_cost] per case. "" is observed. No mutation.19.Retain undefined support in a likelihood-ratio path
Write
ratio_path(rows, threshold). Rows[null_probability,alternative_probability]in[0,1], exact decimals; threshold>0. Start ratio 1; per row multiply alternative/null. Null=0 makes all ratios from that rowNone, even after a zero ratio. Return {"ratios":post-row values,"first":first 0-based row with defined ratio>=threshold orNone}. Initial 1 is not checked. No mutation.20.Compute distance to a supplied linear score boundary
Write
boundary_radius(weights, point, bias). Equal-length finite decimal vectors define score=bias+sum(w*x). Returnabs(score)/sum(abs(w)), the supplied L-infinity distance to the zero-score boundary. If score=0 return 0 even with zero weights; if weights have zero norm but score!=0 returnNone. Interpret decimals exactly. Only the given linear function. No changes.21.Keep failure brackets and observed monotonicity conflicts
Write
failure_bracket(rows). Rows[unique_finite_input,failed_bool_or_None]assert nondecreasing failure. IgnoreNone. Return {"pass":greatest observed passing input orNone,"fail":least observed failing input orNone,"contradictions":[failed_input,passing_input]for every failed input below a passing one, sorted}. Keep conflicting bounds; do not infer unobserved outcomes or mutate.22.Measure transport across irregular ordered error support
Write
ordered_transport(points, left, right). points strictly increases; aligned nonnegative finite decimal masses need not sum to 1. Normalize each side by its own positive total, then sumabs(left_CDF[i]-right_CDF[i])*(points[i+1]-points[i]) for i before the last point. ReturnNoneif either mass total is zero, also empty input. Interpret decimals exactly; do not assume equal spacing or mutate.23.Reconcile within-cohort and composition changes
Write
cohort_decomposition(rows): cohort->[old_weight,new_weight,old_rate_or_None,new_rate_or_None], exact decimals. Nonnegative weights sum to 1 per side. Positive weight on either side needs both rates, elseNone; ignore zero/zero cohorts. Return {"within":sum(avg_weight*(new_rate-old_rate)),"composition":sum(avg_rate*(new_weight-old_weight)),"total":new_mean-old_mean}. Empty:None. No mutation.24.Rank frozen review draws by an explicit weighted priority
Write
review_priorities(rows, k). Rows[unique_string_id,weight>0,draw]contain finite numbers and 0<draw<=1; k>=0. Compute each priority exactly as Pythonmath.log(draw)/weight. Return first k ids by descending priority, ties by id; k may exceed row count. Draws are supplied and must not be resampled. This task specifies a priority kernel, not an inclusion-probability guarantee. No mutation.25.Choose review cases by distinct covered error kinds
Write
review_cover(rows, budget). At most 16 rows[unique_string_id,integer_cost>=0,error_kind_list]; budget>=0. Choose a subset within budget maximizing distinct covered kinds, then minimizing cost, case count, and sorted ids lexicographically. Return{"ids":sorted selected ids,"cost":total,"covered":sorted union}. Repeated kinds add no value; empty subset is allowed. No mutation.26.Separate outer held-out leakage from inner split overlap
Write
nested_split_audit(outer_test, inner).outer_testlists ids; inner maps fold names to{"train":ids,"validation":ids}. Return {"outer":[fold,id]when an outer-test id occurs in either inner role,"overlap":[fold,id]when an id occurs in both inner roles}, both sorted by (fold,id). Deduplicate repeated ids. An id can appear in both reports; do not silently move examples or mutate.27.Optimize one-to-one alignment of unsupervised cluster labels
Write
cluster_alignment(reference, clusters). Equal-length string-label lists have K<=7 distinct labels each. Bijection from sorted cluster labels to reference labels maximizes paired agreement; ties use lexicographically smallest assigned-label tuple. Return {"mapping":[cluster,reference_label]sorted by cluster,"accuracy":agreement/N orNonefor N=0}. For unsupervised identifiers. No mutation.28.Measure both uniform empirical-CDF deviations
Write
uniform_distance(values). Finite supplied probability-integral values lie in[0,1]. Sort tou[1..n]. Return{"plus":max(i/n-u[i]),"minus":max(u[i]-(i-1)/n),"distance":max(plus,minus)}using exact decimals. Empty input returnsNonein all fields. Both sides of empirical jumps matter, including repeated/end values. Compute no p-value or assumption validation. No mutation.29.Correlate midranks while preserving tied observation support
Write
rank_association(left, right). Equal-length finite lists. Replace each value with its mean 1-based position among equal values in ascending order. Return Pearson correlation of the two rank vectors: centered cross-product divided bysqrt(product of centered sums of squares). ReturnNonefor n<2 or either constant rank vector. No no-ties shortcut or p-values. No changes.30.Update weighted pairwise preferences from frozen log-worths
Write
preference_step(theta, rows, rate). theta maps models to finite log-worths; rows[a,b,y,weight]use distinct known models, y in{0,.5,1}, weight>=0; rate>=0. From frozen theta, p=sigmoid(theta[a]-theta[b]); add weight*(y-p) tog[a], subtract it fromg[b]. Return [model,theta[model]+rate*g[model]] sorted by model. Sum all rows before updating; use a stable sigmoid. No mutation.