← Gym/k-Means from Scratch
00:00/ 30 min

🧭 Do not search for the first 15 minutes. When stuck: re-read the requirements → define I/O → choose the data structure → trace a small example by hand → write code.

Find clusters with Lloyd's algorithm. k-means normally seeds its centroids at random, but this problem has no randomness — the initialization is fixed so the answer is unique.

Input

python
X      # (n, d) real-valued features
k      # cluster count (at least 1, at most n)
iters  # iteration count (0 or more)

If X arrives one-dimensional, treat it as (n, 1).

Algorithm

  • The initial centroids are the first k rows of X. They are not sampled.
  • Repeat these two steps exactly iters times:
    1. Assign — attach each point to its nearest centroid (Euclidean, square root included). On equal distance, the lower centroid index wins.
    2. Update — move each centroid to the mean of its cluster.
  • An empty cluster keeps its centroid — if no point is assigned to it, leave the coordinates as they were. Without this rule you divide by zero.

With iters=0 the initial centroids are the answer.

Return

kmeans(X, k, iters) → a list of k centroid coordinates (each a list of length d), every float rounded to 6 decimal places.

Level 1 · Lloyd iterations

Implement kmeans(X, k, iters).

  • The initial centroids are the first k rows of X — not random.
  • Assign, then update, exactly iters times.
  • On a distance tie, the lower centroid index wins.
  • An empty cluster keeps its centroid (do not divide by zero).
  • Return k coordinate lists, each value round(v, 6).