PIXELBANKv9.1.0
Menu

K-Means Assignment Step

Implement the assignment step of the K-Means algorithm.

Given data points and current centroids, assign each point to the nearest centroid using Euclidean distance.

Return a list of cluster assignments (0-indexed centroid indices). If a point is equidistant from multiple centroids, assign it to the one with the smallest index.

Example:

Input:
X = [[1, 0], [2, 0], [8, 0], [9, 0]]
centroids = [[1.5, 0], [8.5, 0]]
Output:
[0, 0, 1, 1]
Reasoning:
  • We calculate the Euclidean distance from each data point to the centroids. For the first data point [1, 0], the distance to the first centroid [1.5, 0] is d=(1−1.5)2+(0−0)2=(−0.5)2=0.5d = \sqrt{(1-1.5)^2 + (0-0)^2} = \sqrt{(-0.5)^2} = 0.5 and to the second centroid [8.5, 0] is d=(1−8.5)2+(0−0)2=(−7.5)2=7.5d = \sqrt{(1-8.5)^2 + (0-0)^2} = \sqrt{(-7.5)^2} = 7.5.
  • We assign each data point to the centroid with the smallest distance. The first data point [1, 0] is assigned to the first centroid (index 0) since 0.5<7.50.5 < 7.5.
  • We repeat this process for the remaining data points: [2, 0] is assigned to the first centroid (index 0), [8, 0] is assigned to the second centroid (index 1), and [9, 0] is assigned to the second centroid (index 1).
  • The final output is a list of these assignments: [0, 0, 1, 1]

Constraints:

  • X: 2D list of data points (n x d)
  • centroids: 2D list of centroid positions (k x d)
  • Return list of n integers (cluster assignments, 0-indexed)
solution.py

Test Results

0/0
Run code to see test results.
K-Means Assignment Step - Easy | PixelBank