Classify with nearest neighbours
Nearest-neighbour classification stores examples rather than fitting weights. Distance chooses nearby observations, and a vote chooses their label. Ties need deterministic rules: equal distances follow training order here, and equal vote counts choose the smaller label. Squared distance is sufficient because square root preserves the order of nonnegative distances.
point = (2, 3)
other = (5, 7)
print(sum((a-b)**2
for a,b in zip(point, other)))Think before coding
Sorting indices preserves alignment between features and labels. Stable ordering and an explicit vote tie-break make predictions reproducible. Feature scales strongly affect this distance, so preprocessing is part of the model design. Work through the example by hand before changing the starter. Decide what should happen for an empty input, a single value and a repeated value where those cases apply. The checks use several inputs so a hard-coded answer cannot stand in for the rule.
Your task
Write nearest_label(points, labels, query, k) for numeric vectors of equal dimension and integer labels. Use up to k nearest points (stable training order for distance ties), majority vote, then smaller label for vote ties. Reject k <= 0 or empty training data.
The explanation opens here once every check passes.