K-Means: The Centroid Update

Classic MLMedium+15 XP+15

K-Means: The Centroid Update

K-means alternates between two moves until nothing changes. The first assigns every point to its nearest centroid. This is the second: move each centroid to the average of the points that chose it.

Task: write update_centroids(points, assignments, centroids) returning the new centroid positions, every coordinate rounded to 4 decimal places.

  • points is a list of points; assignments[i] is the cluster number that points[i] was assigned to; centroids holds the current positions, so centroids[c] belongs to cluster c.
  • A cluster's new position is the coordinate-wise mean of its members: average all their first coordinates, average all their second, and so on.
  • If no point chose a cluster, that cluster keeps its current position. There's no average to take, and you must not divide by zero or quietly drop the cluster — the output always has one centroid per input centroid, in the same order.
  • Points can have any number of dimensions.

That empty-cluster rule is a real decision, not a formality. A centroid nobody wants is a sign your k is too high or the initial positions were unlucky; leaving it parked is the gentlest of several possible responses, and it keeps the algorithm's shape intact.

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 = [[1, 1], [3, 3], [10, 10]]
assignments = [0, 0, 1]
centroids = [[0, 0], [9, 9]]
returns [[2.0, 2.0], [10.0, 10.0]]
points = [[1, 1], [2, 2]]
assignments = [0, 0]
centroids = [[5, 5], [7, 7]]
returns [[1.5, 1.5], [7.0, 7.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