FreeExam

Feature Contract Validation

Thirty original Python problems on feature types, missing and ambiguous support, schema and vocabulary evolution, exact units, temporal contracts, joins and constrained transforms. Implement explicit finite models and preserve the evidence behind every decision.

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

  1. 1.Keep type, null and absence failures separate

    Write cell_errors(rows,schema,allow_extra). Schema maps names to [kind,required,nullable], kind int/number/text/bool. Int excludes bool; number accepts finite int/float excluding bool. Return [row,field,reason], row then field order. Reasons: missing for absent required, null for forbidden None, type for wrong nonnull kind, extra for undeclared if forbidden. Optional absence is valid. No mutation.

  2. 2.Project nested cells without erasing present nulls

    Write project_paths(record,paths). Each path is a list of string dict keys or nonnegative integer list indices; bool is not an index. A token on the wrong container or out of bounds means missing. Empty path selects the whole record. Return [found,value] for each path, using [False,None] when missing and detached copies when found. No mutation.

  3. 3.Retain forced bindings across all header assignments

    Write header_bindings(headers,aliases), <=6 unique headers and <=6 required names. Aliases maps required names to accepted headers. Assign every required name to distinct headers. Return [count,forced_pairs], pairs [required,header] common to all assignments, sorted by required; return [0,[]] if impossible. Extra headers need not be used. Empty requirements: one assignment. No mutation.

  4. 4.Bind shared dimension symbols across feature tensors

    Write bind_shapes(actual,specs). Maps feature names to dimension lists; actual sizes are nonnegative integers. Spec dimension: fixed nonnegative int, "*" for any size, or another string naming a globally shared size. All spec features must exist and ranks/fixed/shared sizes must agree; extra actual features are ignored. Return sorted [symbol,size] bindings, or None on any failure. No mutation.

  5. 5.Audit composite keys with type-sensitive identity

    Write key_groups(rows,fields). Selected cells are JSON null, bool, integer or string; fields are unique. Rows missing any selected field are invalid. Compare keys by exact type AND value, so True differs from 1. Return [invalid_indices,duplicate_index_groups], each group in input order, groups by first index. Empty fields give all rows the same key. No mutation.

  6. 6.Find integer values lost by a domain migration

    Write lost_ranges(old,new). Each list contains closed integer intervals [lo,hi] with lo<=hi, possibly unsorted/overlapping. Return sorted maximal closed intervals accepted by old but not new. Adjacent integer intervals coalesce. Do not enumerate individual values; endpoints may be large. Empty domains are allowed. No mutation.

  7. 7.Preserve unknown and removed vocabulary-code states

    Write remap_codes(codes,old,new). Vocabularies contain unique strings; codes are integers. -1 means unknown and remains -1. Valid old indices map by token identity to new indices; removed tokens become -2. Other input codes yield None. Return [mapped,removed_input_indices,invalid_input_indices]. Reordering must not change token meaning. No mutation.

  8. 8.Convert nullable integer features with exact affine units

    Write convert_column(values,source,target,units). Units maps names to [dimension,mul_num,mul_den,offset_num,offset_den], positive multipliers/denominators. Base=x*mul+offset. Values are integers or None. Unknown units or different dimensions return None. Otherwise return reduced [numerator,denominator] target values, keeping None. Use exact arithmetic and do not mutate inputs.

  9. 9.Fill absent features and retain insertion provenance

    Write fill_absent(rows,defaults). For each row, insert a detached copy of each default ONLY if its key is absent; existing None, False, 0 and empty containers remain unchanged. Return [copied_rows,insertions], insertions [row_index,key] ordered by row then key. Every output row and nested value must be detached from inputs and other inserted defaults. No mutation.

  10. 10.Audit joint absence and null budgets exactly

    Write missingness_budget(rows,limits). Limits maps feature to [numerator,denominator], 0<=num<=den and den>0. Return sorted [feature,absent_count,null_count,exceeded]. Exceeded means (absent+null)*den > row_count*num, with equality allowed. All rows form the denominator; nonnull falsey values are supported. No rows means zero counts and no exceedance. No mutation.

  11. 11.Apply conditional field obligations only with evidence

    Write obligation_errors(rows,rules). A rule is [condition_field,condition_value,target,allowed_values]. All compared values are strings or None. Trigger only when the condition field exists and equals its value. Triggered target must exist and belong to allowed_values. Return [row_index,rule_index,"missing"/"value"] in row/rule order. A present null may trigger or satisfy a rule. No mutation.

  12. 12.Separate unsupported sums from tolerance violations

    Write sum_errors(rows,parts,total,tolerance), tolerance>=0 integer. Declared operand cells are integers or None; parts is a unique field list and total is another field. A row with any absent/null operand is unsupported. Otherwise require abs(sum(parts)-total)<=tolerance. Return [violated_indices,unsupported_indices]. Empty parts sums to zero. No mutation.

  13. 13.Find differing-value witnesses for a feature dependency

    Write dependency_witnesses(rows,keys,value). Complete key cells are strings; value is string or None. Missing keys/value make a row unsupported. Within each exact key tuple, report every pair i<j whose values differ. Return [unsupported_indices,pairs], pairs sorted lexicographically by row indices. Empty keys group all complete rows together. No mutation.

  14. 14.Audit adjacent observed feature events per entity

    Write history_errors(events), rows [entity,time,sequence] with integer time/sequence. Relative to the immediately preceding input event for that entity, time must not decrease; at equal time sequence must strictly increase. A newer time allows any sequence. Return indices violating this rule. Even a violating event becomes the next observed predecessor. Preserve input order; do not sort or mutate.

  15. 15.Resolve feature support under two independent cutoffs

    Write asof_support(rows,queries). Rows [key,event_time,observed_time]; queries [key,event_cutoff,knowledge_cutoff], all times integers. Eligible rows match key and both times <= their cutoffs. Maximize (event_time,observed_time). Return ["ok",[index]], ["ambiguous",best_indices] or ["missing",[]] per query. Equal-best rows remain ambiguous even if identical. No mutation.

  16. 16.Retain overlapping feature-validity support

    Write validity_support(segments,queries). Segments [key,start,end], integer start<=end, represent [start,end). Queries [key,time]. Return all supporting segment indices for each query in input order: [] means missing, multiple indices mean ambiguous. Zero-length segments never support a query. Do not choose one overlap, sort source rows, or mutate.

  17. 17.Audit feature time evidence without hiding multiple failures

    Write freshness_reasons(rows,now,max_age,max_delay), rows [event,observed] integers, nonnegative age/delay limits. Return a reason list per row, in this order: future-event if event>now; reversed if observed<event; future-observation if observed>now; stale if now-event>max_age; delayed if observed-event>max_delay. Evaluate all predicates independently; equal limits pass. No mutation.

  18. 18.Find value conflicts within signed feature-grain buckets

    Write grain_conflicts(rows,width,origin), width>0 integer, rows [entity,time,value] with integer times and string values. Bucket start=origin+floor((time-origin)/width)*width. Return [entity,start,sorted_distinct_values] only for buckets with >1 distinct value, sorted by entity then start. Repeated equal values are not conflicts. No mutation.

  19. 19.Invert finite offset segments without inventing support

    Write local_candidates(segments,times). Segments [utc_start,utc_end,offset] are disjoint half-open integer UTC ranges, utc_start<=utc_end. Inside a segment local=utc+offset. For each integer local time return sorted distinct UTC candidates supported by the table. Gaps yield []; folds can yield several. No extrapolation or real timezone-library equivalence. No mutation.

  20. 20.Audit feature cadence without coercing off-grid rows

    Write cadence_support(start,step,count,samples), step>0, 0<=count<=1000, integer samples. Expected times are start+i*step for i in range(count). Return [missing_times,duplicate_times,off_grid_indices], times sorted. Duplicate means >1 sample at an expected time; off-grid duplicates stay indexed only as off-grid. No mutation.

  21. 21.Apply grouped aggregation support and null policies

    Write aggregate_features(rows,operation,null_policy,min_count), rows [group,integer_or_None], operation sum/mean, policy ignore/propagate, min_count>=0. For sorted groups return [group,result,nonnull_count,null_count]. Result is reduced [num,den], or None if count<min_count, mean has zero count, or propagate sees null. Ignore sum of only nulls is [0,1] when min_count=0. No mutation.

  22. 22.Intersect contract support across required partitions

    Write shared_versions(required,announcements). Required is a list of partition names, repetitions ignored. Announcements [partition,version] use string versions; duplicates add no support. Return sorted versions announced for EVERY required partition. Missing partitions give []; empty requirements also give [] because no version universe is supplied. Ignore unrequested partitions. No mutation.

  23. 23.Audit producer states against consumer acceptance

    Write compatibility_errors(producer,consumer,allow_extra). Maps list possible/accepted states from int,float,text,bool,null,absent; duplicates ignored. For every consumer field, missing producer declaration means [absent]. Report [field,sorted_rejected_states]. Producer-only fields: ignore if allow_extra, else reject every state except absent. Omit empty reports; sort by field. No mutation.

  24. 24.Validate ordered feature layouts through explicit transforms

    Write transform_layout(columns,steps), unique initial names. Steps [rename,old,new], [drop,name] or [select,names_list]. Rename requires old and a free new name unless unchanged. Drop requires the name. Select requires distinct existing names and sets their specified order. Return [final_columns,None], or [None,first_invalid_step_index]. No partial output on failure. No mutation.

  25. 25.Propagate declared feature tags through cyclic dependencies

    Write propagate_tags(base,dependencies). Base maps feature to string tags; dependencies maps output to input-name lists. Every mentioned name is a feature. Output tags are own base tags UNION all input tags, until stable; cycles allowed. Return sorted [feature,sorted_tags]. Duplicates collapse; unseeded cycles have no tags. This is declared-tag propagation, not privacy certification. No mutation.

  26. 26.Audit key cardinality separately from left-join expansion

    Write join_contract(left,right,relationship), key lists contain strings or None. Null never matches. Relation: one-to-one/many-to-one/one-to-many/many-to-many: one requires <=1 nonnull occurrence per key on its side, including unmatched keys. Return [bad_left_keys,bad_right_keys,row_count], sorted bad keys. Left null/unmatched keys give one row each; matches form Cartesian products. No mutation.

  27. 27.Align feature batches with row order and null support

    Write align_batch(batch,order). Batch maps feature to [row_id,value] records; row IDs are unique per feature, values JSON. Return [sorted_features,matrix,missing_pairs]. Matrix follows requested order (including duplicates), columns sorted features; missing cells use None but also report [output_row,column_index]. Present None is supported. Return detached nested values. No mutation.

  28. 28.Choose defaults from explicit local or global support

    Write choose_defaults(rows,groups,min_support), rows [group,string_or_None], min_support>=1. Count nonnull occurrences. For each queried group use its local data if count>=min_support; otherwise global data if count>=min_support; otherwise [None,"unsupported"]. A unique mode returns [value,"local"/"global"]; a tied mode returns [None,"tie"] with NO fallback. Preserve query order. No mutation.

  29. 29.Find a contract witness and all supported marginal values

    Write feasible_contract(domains,constraints). <=6 feature names, each <=4 distinct integers. Constraints [a,op,b], op <,==,!=, reference declared features. Return None if infeasible. Otherwise return [lexicographically_smallest_value_list,marginal_supports], in sorted feature order; supports list ALL values used by any valid assignment, sorted. Empty contract gives [[],[]]. No mutation.

  30. 30.Check dimensions through feature expression trees

    Write expression_dimension(tree,units). Units maps columns to {base:integer_exponent}. Tree: [col,name], [add,left,right], [mul,left,right], [div,left,right], [pow,child,integer_power]. Add requires equal dimensions; mul/div add/subtract exponents; pow scales. Unknown column/invalid addition returns None even under power zero. Else sorted nonzero [base,exponent]; [] is dimensionless. No mutation.