Back to Practice
#0121

Label Encode Train and Test

MediumML25 min20 XP

Problem

Given train and test category lists, map sorted train categories to integer ids starting at 0. Unknown test categories should become -1. Return encoded_train, encoded_test, mapping.

Why This Matters

Encoders must be fit on training data and then applied consistently to validation/test data.

Function Signature

def label_encode_train_test(train, test):

Examples

Example 1
Inputtrain=["b","a","b"], test=["a","c"]
Output([1,0,1], [0,-1], {"a":0,"b":1})

c is unknown because it appears only in test.

Constraints

  • Return the requested value exactly.
  • Handle the stated edge cases.
  • Keep the solution readable.
CodePython
Visible browser tests run here when available.
Testcases1 visible / 3 hidden categories
Core example
Inputtrain=["b","a","b"], test=["a","c"]
Expected([1,0,1], [0,-1], {"a":0,"b":1})

c is unknown because it appears only in test.

Hidden Test Categories
empty testsingle train categoryunknown category