Back to Practice
#0172
Label Encode Train and Test Safely
MediumML25 min20 XP
Problem
Given train categories and test categories, encode train categories from 0 upward and encode unknown test categories as -1.
Why This Matters
Encoders must be fit on training data only; unseen production categories need a deliberate fallback.
Function Signature
def label_encode_train_test(train_values, test_values):
Examples
Example 1
Inputtrain = ['red','blue','red'], test = ['blue','green']
Output([0, 1, 0], [1, -1])
green was unseen during training, so it becomes -1.
Constraints
- Return the exact requested output.
- Handle ordinary edge cases.
- Prefer simple, interview-readable code.
CodePython
Visible browser tests run here when available.
Testcases1 visible / 3 hidden categories
Core example
Inputtrain = ['red','blue','red'], test = ['blue','green']
Expected([0, 1, 0], [1, -1])
green was unseen during training, so it becomes -1.
Hidden Test Categories
empty or minimal inputduplicates or tieslarger input