K-Means: The Assignment Step

Classic MLEasy+10 XP+10

K-Means: The Assignment Step

K-means alternates between two moves until nothing changes: assign every point to its nearest centroid, then move each centroid to the mean of the points that chose it. This is the first half.

Task: write assign_clusters(points, centroids), where both are lists of equal-length coordinate lists. Return a list of integers — for each point, the index of its closest centroid by Euclidean distance.

  • If a point is exactly equidistant from two centroids, pick the lower index.
  • Points and centroids can live in any number of dimensions, not just 2.

The comparison never needs an actual square root — whichever centroid is nearest by squared distance is nearest by distance too. Skipping it is the standard optimisation here.

Assign, Then Move, Then Repeat

Step through K-Means one move at a time. Watch how far the centroids have to travel from their random starting spots.

Iteration 0: each point is about to join its nearest centroid.

Examples

points = [[0.0, 0.0], [5.0, 5.0]]
centroids = [[0.0, 0.0], [5.0, 5.0]]
returns [0, 1]
points = [[1.0, 1.0], [4.0, 4.0], [0.5, 0.2]]
centroids = [[0.0, 0.0], [5.0, 5.0]]
returns [0, 1, 0]

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