FreeExam

Data Validation Functions

Original Python data analyst interviews on scalar and schema contracts, relational evidence, missing support, rule logic, and bounded consistency witnesses.

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

  1. 1.Keep missing, null, blank and observed scalars distinct

    Write field_states(rows, field). rows contains flat objects with JSON scalar values. Return one status per row in input order: "missing" if field absent, "null" for None, "blank" for a string empty after Python str.strip(), otherwise "present". Numeric 0, False and nonblank strings are present; do not coerce scalars to strings or mutate.

  2. 2.Audit required presence and unexpected row columns

    Write column_contract(rows, required, optional). required/optional are disjoint unique field-name lists. For each object return [row_index,sorted_missing_required,sorted_unexpected] only if either list is nonempty. A present None satisfies column presence; value validity is separate. Allowed fields are exactly required+optional. Preserve row order, compare names exactly, and do not mutate.

  3. 3.Validate JSON scalar domains without boolean-number leakage

    Write scalar_matches(values, kind). Finite JSON scalars; kind is "integer","number","boolean","string" or "null". Return booleans per input. Number accepts numeric values except bool; integer accepts those numbers with zero fractional part, including 2.0. Boolean accepts only bool; string only str; null only None. No coercion/mutation. JSON numbers compare by value, not Python storage type.

  4. 4.Validate explicit decimal syntax before exact range checks

    Write decimal_tokens(tokens, low, high). String tokens use ASCII grammar: optional +/-, then one or more digits, optionally a dot followed by one or more digits. No whitespace, exponent or separators. Bounds are finite exact decimals, low<=high. Return {"syntax":bad-format indices,"range":well-formed out-of-range indices}, each in input order. Compare inclusive bounds exactly; no mutation.

  5. 5.Check date spelling separately from calendar validity

    Write date_checks(tokens). String tokens must have exactly ASCII YYYY-MM-DD spelling and form a valid Gregorian date with year 1..9999. Return {"format":wrong-shape indices,"calendar":correct-shape but invalid-date indices}, in input order. Compact dates, alternate widths and surrounding whitespace fail format. Do not normalize invalid input or mutate.

  6. 6.Keep key components separate when finding collisions

    Write key_collisions(rows, columns). Equal-width rows contain strings or None; columns lists unique valid indices. A key with any selected None is incomplete. Return {"duplicates":[key_components,row_indices] for complete keys appearing >1 time, sorted lexicographically by key,"incomplete":row indices in input order}. Empty columns give one shared complete empty key. No mutation.

  7. 7.Retain every conflicting dependent-value witness

    Write dependency_conflicts(rows). Rows [determinant,dependent], strings or None. Either None makes a row unsupported. For determinants with >1 distinct supported dependent, report [determinant,[[dependent,row_indices],...]], sorted by determinant/dependent. Return {"conflicts":these groups,"unsupported":input indices}. Repeats retain row witnesses but add no distinct value. No mutation.

  8. 8.Separate ambiguous parent identities from unknown references

    Write reference_states(parents, children). parents lists string ids, possibly repeated; children lists string ids or None. Return [status,parent_index_or_None] per child: None is "null"; no parent "unknown"; >1 parent rows "ambiguous"; one parent "matched" with its index. Preserve child order. Empty-string ids are observed. Do not select one duplicate parent as a valid resolution. No mutation.

  9. 9.Audit prospective join expansion without materializing pairs

    Write join_audit(left, right). Key lists contain strings or None; None never matches. Return dict keys pairs (matched pair count), left_unmatched/right_unmatched (input indices with no match), left_expanded/right_expanded (indices matching >1 opposite rows). Duplicate keys multiply pairs; expansion is per input row, not per key. All index lists ascend. No mutation.

  10. 10.Traverse explicit paths without collapsing null and missing

    Write path_values(record, paths). Nested JSON record; paths list string keys or integer indices, no bool. Dict+string and list+nonnegative index are valid steps. Absent keys/out-of-range indices give ["missing",None]; wrong container/step type ["blocked",None]. Otherwise ["present",value], including None. Empty path selects record. Preserve path order; no mutation.

  11. 11.Expose raw category labels lost under normalization

    Write category_collisions(labels). String labels normalize by str.strip().casefold(). Return [normalized,sorted_distinct_raw_labels] when >1 distinct raw spelling shares a normalized value, sorted by normalized key. Identical repeats alone are not collisions. Include collisions normalizing to empty string. Report evidence without rewriting labels. No mutation.

  12. 12.Validate a supplied quoted-field grammar and record width

    Write delimited_check(line, sep, expected). sep is one char except quote/CR/LF; expected>=1. Reject CR/LF. Fields are unquoted (no quote/sep) or double-quoted with doubled-quote escapes. After closing quote allow only sep/end. Empty/trailing fields count. Return {"fields":count_or_None,"valid":count==expected}; syntax error gives None/False. Supplied grammar, not full CSV. No mutation.

  13. 13.Group deep JSON duplicates without boolean-number collisions

    Write structural_duplicates(values). Finite nested JSON values only; object keys strings. Equality ignores object key order but preserves array order and scalar domains: bool differs from number, None from other values. Equal-valued JSON numbers (1 and 1.0) are equal. Return lists of input indices for groups appearing >1 time, ordered by first index. Do not stringify whole objects or mutate.

  14. 14.Apply state-specific required values without truthiness

    Write conditional_fields(rows, state_field, rules). rules maps string states to required field lists, possibly repeated. State strings/None: absent/None/unknown is unsupported. For known states required fields fail only if absent/None; 0,False,"" are observed. Return {"unsupported":row indices,"missing":[row_index,field]}, rows/fields sorted, duplicate requirements removed. No mutation.

  15. 15.Check displayed percentages with exact half-even ties

    Write percentage_checks(counts, shown, places). Equal-length lists: nonnegative integer counts and finite exact decimal percentages; places integer 0..4. For positive total N, compare shown[i] to 100*counts[i]/N rounded to places using exact nearest, ties-to-even rounding. Return {"mismatched":indices,"unsupported":False}. If N=0 return empty mismatches/unsupported True. No mutation.

  16. 16.Use expected-value scale in absolute-plus-relative checks

    Write tolerance_checks(actual, expected, atol, rtol). Equal-length finite exact decimal/None lists; atol,rtol>=0. Either None makes a pair unsupported. Accept observed pairs iff abs(actual-expected)<=atol+rtol*abs(expected). Return {"mismatched":indices,"unsupported":indices}, each in input order. Expected sets the relative scale; zero is observed. No mutation.

  17. 17.Convert scale and offset before checking target ranges

    Write unit_checks(rows, transforms, low, high). Rows [id,unit,value], finite exact decimals; transforms maps unit to exact [scale,offset]; low<=high. Convert value*scale+offset. Return [id,status,converted_or_None] in input order: "unknown" for undeclared unit, "valid" within inclusive target bounds, else "out_of_range". Retain known conversions even out of range. No mutation.

  18. 18.Retain row-shape and null-cell diagnostics independently

    Write matrix_checks(rows, width). width>=0 integer; each row is a list of JSON scalars or a scalar. Return {"not_lists":scalar-row indices,"wrong_width":[list_row_index,length] when length!=width,"null_cells":[row,column] for None cells in EVERY list row, even wrong-width rows}. All reports follow row/column order. Empty lists are valid rows when width=0. No mutation.

  19. 19.Reconcile unseen, novel and null category evidence

    Write domain_coverage(declared, values). declared lists unique strings; values lists strings or None. Return {"unseen":sorted declared labels never observed,"novel":[label,row_count] for undeclared observed strings sorted by label,"missing":None indices in input order}. Repeated values count as rows in novel evidence; labels are exact and empty string is observed. No mutation.

  20. 20.Retain full support in descriptive distribution distance

    Write category_distance(reference, counts). Both maps have nonnegative finite exact weights; counts are integers. Normalize each map by its own total. Return half the sum of absolute probability differences over the UNION of keys, treating absent keys as zero. If either total=0 return None. This is descriptive total variation, with no sampling test, smoothing or mutation.

  21. 21.Count joint support without treating zero as null

    Write support_table(rows, first, second). Objects have JSON scalar values. A field is observed iff its key exists and its value is not None; blank strings,0,False are observed. Return a 2x2 count matrix: row index 0=first observed,1=first missing; column 0=second observed,1=second missing. Missing includes absent or None. If first==second, off-diagonal cells are 0. No mutation.

  22. 22.Run rules only after all declared prerequisites resolve

    Write rule_order(rules). rules maps ids to prerequisite id lists, possibly repeated/undeclared. Repeatedly emit the smallest lexicographic un-emitted rule with ALL prerequisites already emitted. Return {"order":emitted ids,"blocked":sorted remaining declared ids}. Cycles, self-dependencies and undeclared prerequisites block affected rules and dependents. No invented rules. No mutation.

  23. 23.Find a smallest deterministic cover of row conflicts

    Write quarantine_rows(ids, conflicts). ids lists <=16 unique strings; conflicts [known_id,known_id] have distinct endpoints, may repeat. Remove a set so every conflict has a removed endpoint. Return sorted removed ids minimizing count, then lexicographic id list. Isolates need no removal; no conflicts gives []. This is a supplied conflict cover, not proof that removed rows are wrong. No mutation.

  24. 24.Retain unknown rule outcomes unless logic is decisive

    Write evaluate_rules(expr, outcomes). Leaves are rule-id strings, missing ids "unknown". Outcomes are pass/fail/unknown. Valid finite nodes: ["all",...], ["any",...], ["not",child]. all fails if any fail, passes if all pass, else unknown; any passes if any pass, fails if all fail, else unknown; not swaps pass/fail, retains unknown. Empty all passes; empty any fails. No mutation.

  25. 25.Audit validation outcomes as a disjoint complete partition

    Write partition_audit(ids, accepted, rejected). ids lists unique strings; accepted/rejected may repeat or include undeclared ids. Return {"missing":sorted universe ids in neither,"overlap":sorted universe ids in BOTH,"unexpected":sorted ids outside the universe from either}. Deduplicate evidence. Unexpected ids supply neither covered universe rows nor reported overlap. No mutation.

  26. 26.Check a declared identifier residue after format validation

    Write residue_checks(tokens, weights). Nonempty positive-integer weights. String token needs >=2 ASCII digits: body then final check digit. Multiply body digits left-to-right by repeating weights; expected check=(-sum)%10. Return {"format":bad-shape indices,"checksum":well-formed wrong-check indices}, in input order. No trimming/coercion. This toy checksum is not authentication. No mutation.

  27. 27.Detect narrowed support between closed scalar schemas

    Write schema_changes(old, new). Closed schemas map fields to [type,required_bool,nullable_bool]; types integer/number/string/boolean. Preserve old-valid records. Return sorted dict lists: removed=old-only fields; added_required=new-only required fields; narrowed=common fields made required, losing nullability or narrowing type. Only integer->number widens type; equal types allowed. No mutation.

  28. 28.Find all inclusion-minimal keys without concatenation

    Write minimal_keys(rows, columns). <=10 unique field-name columns; each row has these fields with string values; extras ignored. Return all inclusion-minimal column subsets whose projected tuples uniquely identify every row, ordered by size then lexicographically, fields sorted within subsets. For 0/1 rows the empty subset is a key. Duplicate full projections may leave no key. No mutation.

  29. 29.Construct a least-lexicographic feasible range witness

    Write reconcile_ranges(rows, total). Rows [unique_id,integer_low,integer_high], low<=high; total integer. Choose one integer per id within its inclusive range, summing to total. Return [id,value] sorted by id with lexicographically smallest value vector, or None if infeasible. Empty rows gives [] only for total 0. This is a feasible witness, not observed or trusted replacement data. No mutation.

  30. 30.Fit a weighted nondecreasing least-squares witness

    Write monotone_fit(values, weights). Equal-length finite exact decimal lists; weights>0. Return fitted values x minimizing sum(weights[i]*(x[i]-values[i])**2), subject to x nondecreasing. Positive weights make the fit unique. Empty input gives []. Return the proposed fit only; do not sort observations or mutate either input. A fitted ordering is not proof that the source values were wrong.