concept
Clustering and distance
One-dimensional nearest-center assignment and mean update; fixed tie and empty-cluster policy.
Formal Syntax & Structure
artificial-intelligence syntaxartificial-intelligence
lloyd_step(points, centers)Working Example
Example Snippetartificial-intelligence
def lloyd_step(points, centers): if not centers: raise ValueError("At least one center required") groups = [[] for _ in centers] labels = [] for x in points: label = min(range(len(centers)), key=lambda j: (x - centers[j]) ** 2) labels.append(label) groups[label].append(x) updated = [sum(g) / len(g) if g else c for g, c in zip(groups, centers)] return labels, updated
labels, centers = lloyd_step([0, 2, 8, 10], [0, 8])print(labels)print(centers)