Back to Practice
#0016
Assign Points To Nearest Centroid
MediumML22 min15 XP
Problem
Given data points X and centroids, return the index of the nearest centroid for each point using Euclidean distance.
Why This Matters
K-means alternates between assigning points to centroids and moving centroids. This problem teaches the first half clearly.
Function Signature
def assign_clusters(X, centroids):
Examples
Example 1
InputX = [[0,0], [9,9], [1,1]], centroids = [[0,0], [10,10]]
Outputarray([0, 1, 0])
The first and third points are closer to centroid 0; the second is closer to centroid 1.
Constraints
- X is a 2D NumPy array.
- centroids is a 2D NumPy array with the same feature count.
- Return centroid indices as integers.
CodePython
Visible browser tests run here when available.
Testcases1 visible / 4 hidden categories
Two clear clusters
Inputthree points and two centroids
Expected[0, 1, 0]
Each point is assigned to the closest centroid.
Hidden Test Categories
One centroidThree centroidsOne-dimensional pointsTie behavior using argmin first index