K-Means Step
You are implementing the core update step of the K-Means clustering algorithm. K-Means iteratively assigns points to their nearest centroid, then recomputes each centroid as the mean of its assigned points.
Given a list of points and a list of centroids, perform one iteration:
- Assign each point to its nearest centroid by L2 (Euclidean) distance
- Recompute each centroid as the mean of all points assigned to it
- If a centroid has no assigned points, keep it unchanged
Return the new centroids rounded to 6 decimal places.
Note: For ties (equal distances), assign to the lower-indexed centroid.
Example 1
([[1], [2], [4], [5]], [[1], [5]])[[1.5], [4.5]]Points 1,2 nearest to C0=[1], points 4,5 nearest to C1=[5]. New C0=mean(1,2)=1.5, C1=mean(4,5)=4.5.
Example 2
([[0, 0], [1, 1], [2, 2]], [[1, 1], [900, 900]])[[1.0, 1.0], [900.0, 900.0]]All points assign to C0 (far from C1). C0=mean([0,0],[1,1],[2,2])=[1,1]. C1 empty — kept unchanged.
Example 3
([[0], [1], [3]], [[0], [10]])[[1.333333], [10.0]]All 3 points nearest to C0. Mean = (0+1+3)/3 = 1.333333. C1 empty — kept at 10.0.
- ›2 <= n_points <= 100
- ›2 <= k <= 10
- ›1 <= n_dims <= 10
- ›-1000 <= values <= 1000
Reference solution available after you attempt the question.
Ready to solve it?
Start a session on Mockbit #75. Write your code, run it against hidden tests, and get graded with specific critique on each axis.