K-Nearest Neighbours: Who Gets a Vote?

Classic MLMedium+15 XP+15

K-Nearest Neighbours: Who Gets a Vote?

k-nearest-neighbours does no training at all. To classify a new point it simply finds the k stored points closest to it and lets them vote. This problem is the lookup half: finding those neighbours.

Task: write k_nearest(points, query, k) returning the positions of the k closest points to query, ordered nearest first.

Distance is straight-line (Euclidean) distance:

d=∑i(pi−qi)2d = \sqrt{\sum_i (p_i - q_i)^2}d=i∑​(pi​−qi​)2​
  • points is a list of points; query is a single point with the same number of coordinates. Any number of dimensions.
  • Return indices into points, not the points themselves. That's what lets you look up each neighbour's label afterwards.
  • If two points are the same distance away, the one with the lower index comes first.
  • k is never larger than the number of points.

Notice that you never need the square root to decide an ordering — squared distance ranks points identically, since squaring is increasing for non-negative numbers. Skipping the sqrt is the standard optimisation here, and it changes nothing about the answer.

Inside K-Nearest Neighbors

The dashed point is unknown. Find its 3 nearest neighbors and let them vote.

?

Examples

points = [[0, 0], [3, 4], [1, 1], [2, 2]]
query = [0, 0]
k = 2
returns [0, 2]
points = [[1, 1], [-1, -1]]
query = [0, 0]
k = 2
returns [0, 1]

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run