Mockbit/#75
ML CodinghardNumpy~30m

K-Means Step

Problem

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:

  1. Assign each point to its nearest centroid by L2 (Euclidean) distance
  2. Recompute each centroid as the mean of all points assigned to it
  3. 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.

Examples

Example 1

Input: ([[1], [2], [4], [5]], [[1], [5]])
Output: [[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

Input: ([[0, 0], [1, 1], [2, 2]], [[1, 1], [900, 900]])
Output: [[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

Input: ([[0], [1], [3]], [[0], [10]])
Output: [[1.333333], [10.0]]

All 3 points nearest to C0. Mean = (0+1+3)/3 = 1.333333. C1 empty — kept at 10.0.

Constraints
  • 2 <= n_points <= 100
  • 2 <= k <= 10
  • 1 <= n_dims <= 10
  • -1000 <= values <= 1000
Reference solution

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.

Related ML Coding questions
← Back homemockbit.io/q/75
PrivacyTerms© 2026 Mockbit