Assign each point to its nearest centroid (k-means assignment step). For each point compute squared distance to each centroid; assign to the closer one. Library: NumPy vectorized subtraction, np.sum(..., axis=1), np.where. RESULT: cluster assignment list (0/1 per point).

By hand

With NumPy

np.sum((points - c)**2, axis=1) computes squared distances to one centroid for all points simultaneously. np.where applies the threshold.

naive.py
points = [[1,2],[2,1],[1,3],[7,6],[8,7],[6,8]]
c0 = [1, 1]
c1 = [7, 7]
assignments = []
for pt in points:
    d0 = (pt[0]-c0[0])**2 + (pt[1]-c0[1])**2
    d1 = (pt[0]-c1[0])**2 + (pt[1]-c1[1])**2
    assignments.append(0 if d0 <= d1 else 1)
print('RESULT:', assignments)
library.py
import numpy as np
from dalib.display import set_display
set_display()

points = np.array([[1,2],[2,1],[1,3],[7,6],[8,7],[6,8]])
c0 = np.array([1, 1])
c1 = np.array([7, 7])
d0 = np.sum((points - c0)**2, axis=1)
d1 = np.sum((points - c1)**2, axis=1)
assignments = np.where(d0 <= d1, 0, 1).tolist()
print('d0:', d0.tolist())
print('d1:', d1.tolist())
print('RESULT:', assignments)
d0: [1, 1, 4, 61, 85, 74]
d1: [61, 61, 52, 1, 1, 2]
RESULT: [0, 0, 0, 1, 1, 1]

Implementation notes

  • Squared distance is used for comparison (avoids sqrt); ranking is preserved since √a < √b ↔ a < b for non-negative a, b. Cross-reference: euclidean-distance (ch02) for the distance formula.
  • Points [1,2],[2,1],[1,3] cluster tightly around c0=[1,1]; [7,6],[8,7],[6,8] around c1=[7,7] — no ties possible. Picking centroid positions to eliminate ties avoids undefined assignment behavior.
  • This is ONE step of k-means. Full k-means alternates assign↔update until centroids stop moving. Cross-reference: update-centroids (this chapter).