A packing machine measures every fruit as [weight, width, redness] and has to say what kind of fruit it is. It has a list of rows measured by hand, and labels[i] says what kind of fruit rows[i] was.
Rather than compare each new fruit with every hand-measured one, the machine keeps one typical fruit per kind: the vector of the mean weight, mean width and mean redness of all the fruits of that kind. A new fruit gets the kind whose typical fruit is closest to it in Euclidean distance. If two kinds are exactly equally close, it takes the kind whose name comes first alphabetically.
Write sort_fruit(rows, labels, new_fruits) that returns the list of kinds for new_fruits, in order.
The tests build their samples with fruit_samples(n, seed), which returns (rows, labels) and is available in your code.
Examples
Input: rows = [[150, 70, 80], [170, 80, 60], [100, 60, 10], [120, 60, 10]]
labels = ["apple", "apple", "lemon", "lemon"]
new_fruits = [[155, 72, 65], [112, 58, 20], [135, 70, 40]]
Output: ["apple", "lemon", "apple"]
Explanation: the typical apple is [160, 75, 70] and the typical lemon [110, 60, 10].
The third fruit is at squared distance 625 + 25 + 900 = 1550 from the typical apple and
625 + 100 + 900 = 1625 from the typical lemon.
Input: rows = [[0, 0], [4, 0]], labels = ["plum", "cherry"], new_fruits = [[2, 5]]
Output: ["cherry"]
Explanation: both typical fruits are equally close, and "cherry" comes first.
Constraints
1 <= len(rows) == len(labels) <= 10**4, at most 10 kinds;0 <= len(new_fruits) <= 2000- all vectors have the same length, between 1 and 10, with whole-number values between
0and1000 - a tie in the tests is always an exact tie
Goals
- Summarise every class of a labelled dataset by its mean vector
- Label a new vector by the closest class summary
- Break ties between classes with a fixed rule