Customer Segmentation with K-Means
Group customers into 3 clusters using K-Means based on age and spending, and report which customers ended up in the same group together.
Why report groupings instead of raw cluster numbers? K-Means assigns each cluster an arbitrary integer label (0, 1, 2, ...) that isn't guaranteed to come out the same way across every environment, even with a fixed random_state — but WHICH customers end up grouped together is stable. Printing customer-index groups (sorted by their smallest member) sidesteps that arbitrary-numbering issue entirely.
Approach: fit KMeans(nclusters=3, randomstate=42, n_init=10) on the customer data, then group customer indices by their assigned label and sort the groups for a deterministic, label-order-independent result.
Input: No input.
Output: One line: the customer index groups, sorted by each group's smallest index, printed as a Python list of lists.
(none)
[[0, 1, 2], [3, 4, 5], [6, 7]]
Hint 1
model.labels_ gives the cluster label (an arbitrary int) assigned to each customer, in order.
Hint 2
A defaultdict(list) makes it easy to collect customer indices by their label: groups[label].append(idx).
Hint 3
sorted(groups.values(), key=lambda g: g[0]) orders the groups by their smallest member index, avoiding any dependence on the arbitrary label numbers themselves.
The 8 customers form 3 naturally separated groups by age and spending (young/low-spend, middle-aged/high-spend, older/medium-spend), which KMeans(nclusters=3, randomstate=42, ninit=10) finds reliably. Rather than printing the raw (arbitrarily-numbered) labels, grouping customer indices by their label and sorting the groups by their smallest index gives a result that only depends on which customers end up together — not on which integer K-Means happened to call that group — making it safe to grade exact-match.