FreeExam

Dataset Preparation Code

Original Python applied AI interviews on annotation evidence, leakage isolation, frozen training support, text-span provenance, schema audits, aligned batches, and traceable preparation decisions.

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

  1. 1.Resolve latest annotation evidence and equal-time conflicts

    Write annotation_heads(rows). Rows [string_id,integer_revision,string_label] are annotation evidence. Per id use only its greatest revision. Return [id,revision,label_or_None,sorted_distinct_labels] sorted by id; label is None when latest evidence disagrees. Repeated identical latest labels agree; older disagreement is irrelevant. Do not mutate.

  2. 2.Find transitive leakage groups with stable identities

    Write leakage_groups(ids, links). ids lists unique strings; links lists undirected pairs of known ids that must share a split. Return [smallest_member,sorted_members] for each connected component, ordered by smallest member. Include isolated ids; repeated links and self-links change nothing. Connectivity is transitive. Do not mutate.

  3. 3.Place whole groups using remaining split capacity

    Write place_groups(groups, capacity). groups is ordered [unique_string_id,positive_size]; capacity maps split names to nonnegative integer slots. In arrival order, place a group in a split that fits with greatest remaining capacity, ties by split name. Reject it if none fits. Return {"placed":[id,split],"rejected":[ids],"remaining":capacities}. Never split a group or mutate.

  4. 4.Fit document-frequency vocabulary from training alone

    Write train_vocabulary(rows, minimum). Rows [split,tokens] use string tokens and split "train", "validation" or "test"; minimum>=1. Count each token at most once per training row. Return [token,document_count] sorted by token, keeping counts>=minimum. Other splits never affect counts or vocabulary, including unseen tokens. Do not mutate.

  5. 5.Delete marked ranges while preserving character provenance

    Write delete_ranges(text, ranges). ranges lists valid [start,end] Python character offsets, 0<=start<=end<=len(text), half-open. Remove the union of marked positions. Return {"text":remaining characters in order,"source":their original indices}. Overlapping, repeated and empty ranges are allowed. Do not trim, normalize or mutate.

  6. 6.Build entity-local histories with an explicit horizon

    Write forecast_windows(rows, width, horizon). Rows [string_entity,integer_time,value] have unique times per entity; width,horizon>=1. Sort within entity by time. For each contiguous width-row history, target the row horizon positions after its last row, if present. Return [entity,target_time,history_values] ordered by entity then target time. Horizon counts rows, not time units. Do not mutate.

  7. 7.Mask supervision outside assistant messages

    Write assistant_targets(messages). Each message is [role,integer_token_list], role "system", "user" or "assistant". Flatten tokens in message order. Return {"input_ids":flat tokens,"labels":the token at assistant positions and -100 elsewhere,"supervised":number of assistant tokens}. Empty assistant messages add no target. Token id 0 is valid. Do not insert separators or mutate.

  8. 8.Audit opposing preference evidence without order artifacts

    Write preference_audit(rows). Rows [prompt,a,b,winner] contain strings; winner is "a" or "b". Equal candidates are invalid. Group other rows by (prompt,sorted candidate pair). Return {"pairs":[prompt,low,high,chosen_or_None,row_count] sorted by key,"invalid":input indices}. chosen is the unique winning text, or None for opposing evidence. Reversed agreeing pairs agree. Do not mutate.

  9. 9.Quarantine JSON lines with explicit error categories

    Write quarantine_lines(lines). lines lists strings, each parsed independently with json.loads. Whitespace-only is "blank"; a JSONDecodeError is "json"; a parsed non-dict is "shape". Return {"records":[1-based line,dict],"errors":[1-based line,reason]} in input order. Other inputs are ordinary finite JSON; do not join lines, require a schema or mutate.

  10. 10.Separate absent fields explicit nulls and extra columns

    Write schema_ledger(rows, fields). rows lists dictionaries; fields lists unique declared names in requested order. Return {"fields":[name,absent_count,null_count,value_count],"extra":[name,row_count] sorted by name}. A declared key with None is null; other values including 0, False, "" and [] are observed. Extra counts ignore values. Do not modify rows.

  11. 11.Expand known labels to unique terminal descendants

    Write terminal_labels(tree, labels). tree maps every known string label to its child labels; it is acyclic and children are known. Empty child lists mark terminal labels. Expand requested labels recursively. Return {"leaves":sorted unique reachable terminals,"unknown":sorted unique requested labels absent from tree}. Shared descendants count once. Unknowns do not block known requests. No mutation.

  12. 12.Freeze training cutpoints before binning held-out values

    Write quantile_bins(train, values, k), finite numeric lists, integer k>=1. Sort n training values. Cut j=1..k-1 is element ceil(j*n/k)-1; retain repeated cuts. A value's bin is the number of cuts <= it. Return {"cuts":cuts,"bins":bins in values order}. With no training values return cuts=[] and every bin None. Do not fit using values or mutate.

  13. 13.Expose canonical text collisions while retaining identities

    Write text_collisions(rows). Rows [unique_string_id,text]. Key: apply unicodedata.normalize("NFC", text), then casefold(), then join whitespace-split words with one space. Return [key,sorted_ids] for keys with at least two rows, sorted by key. Include the empty key if shared. Punctuation stays; do not alter raw text, collapse output identities or mutate.

  14. 14.Resolve same-start aliases before advancing the cursor

    Write alias_spans(text, aliases). aliases lists unique nonempty case-sensitive strings. Scan Python character positions left to right. At the current position, if aliases match, choose the longest, emit [start,end,alias], then advance to end; otherwise advance one character. Return emitted nonoverlapping spans. Matches need no word boundary. Do not mutate.

  15. 15.Measure per-label support without overlapping double counts

    Write label_coverage(spans). Each span is [string_label,start,end], integers 0<=start<=end in one source text, half-open. Return [label,total_covered_characters] sorted by label. Measure the union separately for each label; overlaps between different labels count for each. Empty spans create a label with coverage zero. Do not mutate.

  16. 16.Select tokens with positive character intersection

    Write supervised_tokens(offsets, spans). Both lists contain valid half-open [start,end] Python character ranges. Return indices of positive-length tokens in offsets that have positive-length intersection with at least one span. Keep token order, include each index once, and exclude zero-length tokens even inside a span. Touching endpoints are not intersections. No mutation.

  17. 17.Clip source annotations into a retained interval

    Write rebase_spans(spans, left, right). spans lists [label,start,end] with valid nonnegative half-open source offsets; 0<=left<=right defines the retained source interval. Intersect each span with it; discard zero-length intersections. Return [label,new_start,new_end] in input order after subtracting left. Labels need no sorting or deduplication. No mutation.

  18. 18.Audit within-split repeats and cross-split identities

    Write shard_audit(shards). Each shard is [split_name,list_of_string_ids]. Count every occurrence across shards. Return {"duplicates":[id,total,[[split,count],...]] for totals>1 sorted by id,"cross_split":sorted ids present in multiple distinct splits}. Sort split counts by name. Repeats in one split are duplicates but not cross-split leakage. No mutation.

  19. 19.Filter histories using entity-specific embargo boundaries

    Write embargo_history(rows, queries). rows are [entity,integer_time,payload]; queries are [entity,cutoff,nonnegative_embargo]. For each query return payloads of matching-entity rows with time < cutoff-embargo, sorted by time with input order for ties. Return one list per query in query order. Do not use another entity, include equality, deduplicate or mutate.

  20. 20.Detect exact contiguous evaluation-token exposure

    Write ngram_exposure(train, evaluation, n). train rows are [unique_id,string_token_list]; evaluation is a list of token lists; n>=1. Return [train_id,sorted_evaluation_indices] for training rows sharing any exact contiguous n-token tuple with an evaluation row. Keep train order, include each eval index once, and ignore sequences shorter than n. No mutation or token normalization.

  21. 21.Apply split proposals with ordered protection decisions

    Write apply_moves(current, protected, proposals). current maps ids to split names; protected lists ids; proposals is ordered [id,destination]. For each proposal decide in order: unknown id -> "unknown"; protected -> "protected"; already there -> "unchanged"; otherwise update -> "moved". Return {"assignments":final mapping,"actions":[id,status]}. Later proposals see prior updates. Do not mutate.

  22. 22.Resolve sparse fields at their highest observed priority

    Write priority_fields(rows, fields). Rows [int_priority,dict] hold string values or None; fields are unique names. Per field ignore absent/None, use greatest observed priority, and collect its distinct values. Return [field,priority_or_None,value_or_None,sorted_values] in field order. value is None if unsupported or conflicting. Empty string is observed. Ignore weaker disagreement. No mutation.

  23. 23.Expose evidence fanout overflow instead of truncating it

    Write evidence_join(left, right, limit). left rows [unique_id,key]; right rows [key,payload]; limit>=0. For each left row gather matching payloads in right order, including repeats. Return [id,payload_list,status] in left order: no matches -> [],"missing"; matches>limit -> None,"overflow"; otherwise list,"ok". Do not silently truncate, merge unmatched keys or mutate.

  24. 24.Batch in order using padded rather than raw token cost

    Write padded_batches(lengths, budget). lengths are positive token counts; budget>=1. Greedily append indices while batch_size*max_length<=budget. If the next fits alone but not the batch, flush first. An oversize row flushes the current batch, is rejected, and starts none. Return {"batches":nonempty index lists,"oversize":rejected indices}; preserve order. No mutation.

  25. 25.Align padding masks without treating token zero as empty

    Write pad_examples(rows, width, pad). rows are [token_ids,labels] with equal lengths per row; all entries integers, width>=0. If any row exceeds width return None. Otherwise return {"input_ids":right-padded token rows using pad,"attention_mask":1 for original tokens and 0 for padding,"labels":right-padded label rows using -100}. Preserve original labels including -100 and token 0. No mutation.

  26. 26.Retain a contiguous suffix of complete context turns

    Write whole_context(required, turns, budget). required is mandatory tokens; turns is ordered token lists, oldest first; budget>=0. If required alone is too long return None. Otherwise take newest whole turns backward while they fit, stopping at the first that does not; Do not skip it. Return {"tokens":required followed by kept turns in original order,"turns":kept indices}. No mutation.

  27. 27.Compute weights from declared training-class support

    Write class_weights(rows, classes). rows are [split,label]; classes lists unique labels in requested order. Count only "train" rows whose label is declared. Let N=sum(counts), K=len(classes). Return [label,count,N/(K*count)] per class, with weight None when its count is zero. Held-out and undeclared labels affect neither N nor counts. Empty classes returns []. No mutation.

  28. 28.Resolve weighted evidence with exact ties and abstention

    Write weak_label(votes). votes are [string_label_or_None,nonnegative_finite_weight]; interpret decimal weights exactly. None abstains. Sum weights per observed label, including zero totals. Return {"label":unique largest positive-total label or None for ties/no positive support,"scores":[label,total] sorted by label,"coverage":observed weight/all weight or None if all weight=0}. No mutation.

  29. 29.Allocate unique augmentations in bounded parent rounds

    Write augmentation_rounds(parents, candidates, budget, cap). parents are unique ordered ids; candidates are [known_parent,child_id] in arrival order; budget,cap>=0. For cap rounds visit parents in order, taking each's first remaining child not already selected globally, skipping used ids. Stop at budget. Return [parent,child] selections. A parent gets at most one per round. Do not mutate.

  30. 30.Record all failed gates while counting first exclusions

    Write exclusion_audit(rows, gates). rows are [id,checks_dict] with True/False/None values; gates are unique ordered names. A gate passes only if its value is True; absent keys fail. Return {"kept":ids passing all,"excluded":[id,first_failed,all_failed_in_gate_order],"counts":[gate,first_failure_count] in gate order}. Preserve row order and zero counts; ignore extra checks. No mutation.