PIXELBANKv9.1.0
Menu

Implement the update step of the K-Means algorithm.

Given data points, current assignments, and the number of clusters kk, compute new centroids as the mean of all points assigned to each cluster.

Return the new centroids as a 2D list. If a cluster has no points, keep its centroid at the origin (all zeros).

Round each centroid coordinate to 4 decimal places.

Example:

Input:
X = [[1, 0], [3, 0], [8, 0], [10, 0]]
assignments = [0, 0, 1, 1]
k = 2
Output:
[[2.0, 0.0], [9.0, 0.0]]
Reasoning:
  • The data points are grouped based on their current assignments: cluster 0 has points [[1, 0], [3, 0]] and cluster 1 has points [[8, 0], [10, 0]].
  • For each cluster, the new centroid is calculated as the mean of all points assigned to it: for cluster 0, the centroid is [(1+3)/2,(0+0)/2]=[2,0][(1+3)/2, (0+0)/2] = [2, 0] and for cluster 1, the centroid is [(8+10)/2,(0+0)/2]=[9,0][(8+10)/2, (0+0)/2] = [9, 0].
  • The calculated centroids are then rounded to 4 decimal places, resulting in [[2.0, 0.0], [9.0, 0.0]].
  • Since both clusters have points assigned to them, there's no need to handle the case where a cluster has no points.

Constraints:

  • X: 2D list of data points (n x d)
  • assignments: list of n cluster indices (0 to k-1)
  • k: number of clusters
  • Return 2D list of k centroids, each rounded to 4 decimal places
  • Empty clusters get centroid at origin
🔒

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test Results

0/0
Run code to see test results.
K-Means Update Step - Medium | PixelBank