LearnCoding

One-hot encoding with an unknown bucket

Warm-upPreprocessing, Categorical, Data quality

Problem

Build the vocabulary as the sorted unique values of train_col followed by "<unk>". Return (vocab, rows), where rows one-hot encodes each value of test_col and maps unseen values to the "<unk>" column.

Signature

def one_hot(train_col: list[str], test_col: list[str]) -> tuple[list[str], list[list[int]]]: ...

Examples

The visible tests, as an interactive Python session would show them: each call and the value it should give.

>>> one_hot(['b','a','b'], ['a','b']) == (['a', 'b', '<unk>'], [[1, 0, 0], [0, 1, 0]])
True

>>> one_hot(['b','a'], ['z']) == (['a', 'b', '<unk>'], [[0, 0, 1]])
True

Solve it in your own editor; nothing on this page runs code.

Hints

Vocabulary: sorted unique train values followed by <unk>.

Dict lookup with a default — unseen values map to <unk>.

Return (vocab, rows) where rows are one-hot aligned to that vocab.

Reference solution

def one_hot(train_col, test_col):
    vocab = sorted(set(train_col)) + ["<unk>"]
    idx = {c: i for i, c in enumerate(vocab[:-1])}
    rows = []
    for c in test_col:
        r = [0] * len(vocab)
        r[idx.get(c, len(vocab) - 1)] = 1
        rows.append(r)
    return vocab, rows

What a strong solution covers

  • Deterministic vocabulary order.
  • Dict lookup with a default.
  • Discusses rare-category bucketing, hashing for high cardinality, and serving-time consistency.

Common mistakes

  • building the vocabulary from test data
  • crashing on unseen categories.

Study material compiled with AI: drafted by a local model (Inkling 2 Mini) from public sources, then checked against those sources by independent AI reviewers (Claude) in November 2026. Not reviewed line by line by a person.