FreeExam

Training Data Transformations

Original Python coding interviews on training-only fitting, record contracts, annotation handling, group and time separation, and sequence preparation.

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

  1. 1.Fit feature scaling from training observations only

    Write fit_scale(train, other). train is nonempty rectangular finite numeric/None rows; other has the same width. Per column fit mean and population std from present train values only. No present values: mean 0, std 1; zero std: use 1. Impute None with that mean and scale both sets as (x-mean)/std. Return {"mean":...,"scale":...,"train":...,"other":...}. Do not fit on other.

  2. 2.Preserve absent versus explicitly null fields

    Write project_records(rows, columns, defaults). rows are dicts, columns is a unique ordered string list, and defaults is a dict. Return {"values": aligned rows, "present": Boolean presence rows}. Use an existing field even if None, False or 0; for an absent field use defaults.get(name), or None if no default. Presence records key existence, not the resulting value.

  3. 3.Flatten dictionary leaves with escaped slash paths

    Write flatten_record(record) for a nested dict with string keys and JSON values. Recurse through nonempty dicts only; lists, scalars and empty dicts are leaves. Root path is ""; append "/" plus each key after replacing ~ with ~0 and / with ~1. Return path->leaf mappings. An empty root returns {"":{}}. Do not mutate record.

  4. 4.Reconstruct dictionaries from escaped leaf paths

    Write unflatten_record(flat). Keys are paths made by appending "/" plus each dict key escaped as ~ -> ~0 and / -> ~1. Split paths, then decode ~1 before ~0 in each segment. Rebuild dict nesting; lists and empty dicts remain leaves. Inputs are valid with no ancestor/leaf conflicts. A sole "" path is the root; empty flat returns {}. Do not mutate flat.

  5. 5.Rename columns simultaneously and reject collisions

    Write rename_records(rows, mapping), for dict rows and a string-to-string rename map. Transform every original key once, retaining unmapped keys. Return new rows, or None if two keys in any row would have the same destination. Swaps are allowed and must be simultaneous. Absent source keys do nothing. Do not mutate rows, including when a later row collides.

  6. 6.Reject ambiguous annotation-to-token alignment

    Write token_tags(tokens, annotations). tokens are disjoint [start,end] spans; annotations are [start,end,label], all half-open with start<end and labels not "O". A token gets its fully covering label, or "O" if untouched. Return None if an annotation partly overlaps a token or covering annotations disagree. Equal covering labels are allowed. Return tags in token order.

  7. 7.Serialize turns with assistant-only training labels

    Write assistant_batch(turns, separator). Each turn has role (system, user or assistant) and nonnegative integer tokens. Append its tokens and separator to input_ids. Its labels are the same tokens plus separator for assistant turns, otherwise -100 at every position. Return {"input_ids":...,"labels":...}. Real tokens may equal separator; decide labels from role, not token value.

  8. 8.Build next-token examples within document boundaries

    Write next_token_examples(documents, width). documents is a list of token-id lists and width is a positive integer. For each document in order, emit [context,target] at every start where width context tokens and one following target fit. Advance starts by one. Contexts are copied slices; never cross a document boundary or emit an incomplete context.

  9. 9.Pack whole examples under a token budget

    Write budget_batches(sequences, budget, overhead), with positive integer budget and nonnegative integer overhead. Cost is len(sequence)+overhead. Scan in order; reject an example costing more than budget, otherwise append to the current batch or start a new batch if it would overflow. Return {"batches": index lists,"rejected": indices}. Rejections do not flush the current batch.

  10. 10.Truncate prompts while preserving complete answers

    Write protect_answers(examples, limit). Each example is [prompt_tokens,answer_tokens]; limit is a nonnegative integer. Reject indices whose answer alone exceeds limit. Otherwise retain the whole answer and the rightmost prompt tokens fitting the remaining space. Return {"items": [index,kept_prompt,answer] rows,"rejected": indices}, preserving input order without mutation.

  11. 11.Hold out complete groups using first-seen group order

    Write holdout_groups(rows, count), with [unique_id,group] string rows and nonnegative integer count. Order distinct groups by first appearance and put the last count groups in validation, or all groups if count is larger. Return {"train": ids,"validation": ids}, preserving original row order inside both outputs. count=0 holds out nothing; groups must never straddle outputs.

  12. 12.Separate time intervals with an explicit embargo

    Write purged_split(rows, cutoff, embargo). rows are [id,start,end] with integer start<=end; embargo is a nonnegative integer. Training requires end < cutoff-embargo. Validation requires start >= cutoff. Every other row is purged. Return {"train": ids,"validation": ids,"purged": ids} in input order. Equality at the training boundary does not qualify.

  13. 13.Assign stable buckets from UTF-8 id digests

    Write stable_buckets(ids, buckets), with string ids and positive integer buckets. For each id compute SHA-256 of its exact UTF-8 bytes, interpret the first eight hexadecimal digest characters as an integer, and return that integer modulo buckets. Keep order and repetitions. Do not lowercase, normalize Unicode or use Python’s process-dependent hash().

  14. 14.Resample class pools with deterministic provenance

    Write resample_classes(pools, targets). pools maps class strings to unique id lists; targets maps classes to nonnegative integer draw counts. Cycle requested classes alphabetically, taking one draw per unfinished class per cycle and wrapping within its pool. Return [id,class,one_based_class_draw] rows. A positive target with an absent or empty pool returns None; zero targets need no pool.

  15. 15.Quarantine conflicting annotation ids

    Write annotation_consensus(rows), with [string_id,string_label] entries. Repeated equal labels agree. If an id ever has different labels, exclude it permanently from labels and include it once in conflicts. Return {"labels": consistent id-to-label dict,"conflicts": ids in first-appearance order}. A later return to the first label must not undo a conflict.

  16. 16.Normalize existing weights within each group

    Write normalize_group_weights(groups, weights), with equally long string groups and nonnegative finite weights. Divide each weight by the sum of weights in its own group, retaining original position. A group with total weight zero gets all 0.0 values. Do not replace supplied weights with row counts or normalize the entire collection together.

  17. 17.Combine signed feature collisions from UTF-8 bytes

    Write hashed_features(rows, width), with positive integer width and dict rows of string feature -> finite numeric value. For each key, encode UTF-8 bytes; its bucket is sum(bytes)%width and its sign is +1 for even byte length, -1 for odd. Sum signed values into a new width-length row. Keep zero-valued buckets; empty dicts become zero rows.

  18. 18.Preserve missing and zero-denominator reasons

    Write ratio_features(rows), with [numerator,denominator] pairs of finite numbers or None. Return one {"value":...,"reason":...} dict per pair. If either is None, value is None and reason "missing"; otherwise a zero denominator gives reason "zero" and value None. Else return numerator/denominator with reason None. Missing takes precedence over zero.

  19. 19.Join only strictly earlier feature observations

    Write asof_features(examples, features). Examples are [id,key,time]; features are [key,time,value], with string ids/keys and integer times. For each example choose the same-key feature with greatest time strictly below its time; ties use the last feature arrival. Return [id,value,feature_time] rows in example order, or [id,None,None] when unmatched. None is a valid feature value.

  20. 20.Count prior events in a half-open history window

    Write history_counts(events, queries, width). Both lists contain [string_key,integer_time] rows and width is a positive integer. For each query [key,t], count matching-key events with t-width <= event_time < t. Preserve query order and repeated event multiplicity; event input may be unsorted. Current-time events are excluded.

  21. 21.Compact versioned rows without reviving tombstones

    Write compact_changes(rows). Each row is [string_id, nonnegative_integer_version, deleted_bool, JSON_payload]. Per id retain the greatest version; equal versions use the last arrival. Return {"active": [[id,payload],...], "deleted": [id,...]}, both sorted by id. A winning deleted row excludes that id from active; None is a valid active payload. Do not mutate rows.

  22. 22.Validate required fields without Boolean coercion

    Write validate_schema(rows, schema). schema maps required field names to [kind, nullable], where kind is "int", "float" or "str". None is valid only if nullable; a missing key is always invalid. int requires exact int; float accepts exact int or finite float; neither accepts bool. str accepts strings. Ignore extra fields. Return {"valid": row indices, "errors": [[index, sorted bad fields],...]}.

  23. 23.Expand distinct tags while preserving example mass

    Write expand_annotations(examples, annotations). examples has [unique_string_id, JSON_payload]; annotations has [id, string_tag]. For each example in input order, emit [id,payload,tag,weight] for its distinct tags in first-arrival order. Ignore unknown ids and omit unannotated examples. Each emitted weight is 1 divided by that example's distinct tag count; duplicate annotations add no mass.

  24. 24.Trace validation links through duplicate components

    Write linked_training_ids(train_ids, validation_ids, links). IDs are strings, train_ids are unique, and links are undirected duplicate-ID pairs. Return training IDs connected by any number of links to a validation ID, in training order. A shared ID is connected even without a link. Paths may pass through IDs outside both lists; input pairs may repeat or be self-links.

  25. 25.Build paired sequences from supplied masked spans

    Write corrupt_spans(tokens, spans, sentinels, end_id). tokens are integer IDs; spans are sorted, disjoint, nonempty valid [start,end) index pairs with one supplied sentinel ID each. Replace every span by its sentinel in "input". "target" concatenates each sentinel followed by that span's removed tokens, then end_id. Adjacent spans stay separate; no spans yields target [end_id]. Return both lists.

  26. 26.Quantize with frozen per-feature centroids

    Write quantize_rows(rows, centers). rows are rectangular finite numeric/None values. centers supplies a nonempty strictly increasing finite numeric centroid list per column. Replace each present value by its closest centroid index; equal distances choose the smaller index. None becomes -1. Use supplied centers without refitting. Empty rows and zero-column rows are allowed. Return new rows.

  27. 27.Apply a clipped piecewise-linear feature map

    Write interpolate_values(values, knots). values are finite numbers or None; knots are at least two [x,y] pairs with strictly increasing finite x and finite y. Map interior values by linear interpolation between neighboring knots. Values below/above the x range map to the first/last y. None stays None. Preserve input order and do not modify knots.

  28. 28.Exclude the entire group from target features

    Write group_excluded_encoding(rows, prior). rows are [string_group,string_category,finite_numeric_target]. For each row, average targets from other groups with its category. If none exist, average all other-group targets; if no other group exists, use prior. Return one value per row. Exclude every row in the current group, not just the current observation. prior is finite numeric.

  29. 29.Enumerate pairs across independent groups

    Write contrastive_pairs(rows). Each row is [unique_string_id,string_group,string_label]. For every original-index pair i<j with different groups, emit [id_i,id_j,labels_equal_bool]. Use nested index order: increasing i, then increasing j. Omit same-group pairs even when their labels differ. Do not emit self pairs, reversed pairs, or modify input rows.

  30. 30.Schedule transforms from available feature fields

    Write transform_order(steps, initial). Each step has unique string "name" and lists of string "inputs" and "outputs"; initial lists available fields. Repeatedly run the first remaining step in original order whose inputs are all available, then add its outputs. Run each once; stop if none is ready. Return {"order": run names, "blocked": remaining names in original order}. No-input steps are ready.