PY-75
Select Neighbors and Break Voting Ties
Task
Write select_neighbors_and_vote(distances, labels, k) for one query.
distances is a one-dimensional finite numeric NumPy array of non-negative
values. labels is a one-dimensional sequence of strings with the same
length. There is at least one reference item. k is an integer with
1 <= k <= len(distances). If an input violates this contract, raise
ValueError with "invalid neighbor vote".
Return a dictionary with indices, neighbor_labels, counts,
distance_totals, and label:
indicesis a new integer NumPy array of the selected reference indices;neighbor_labelsis a tuple of their labels in selection order;countsmaps each label appearing among those neighbors to its number of appearances;distance_totalsmaps the same labels to the sum of their selected distances;labelis the final voted label.
Apply these rules in order:
- Select the
ksmallest distances. Equal distances are ordered by the smaller original index, so selection is stable. - Find the labels with the largest count among the selected neighbors.
- If several labels remain, keep the label with the smallest
distance_totalsvalue. - If the total distances are still equal, choose the lexicographically smallest label using ordinary Python string ordering.
The returned indices must be in ascending distance/index order. Do not change the input arrays or label sequence.
Example
For k=3, the selected indices are [2, 0, 1]. Label a appears twice and
wins before the final tie rules are needed. If two labels both occur twice and
their selected distance totals are equal, the alphabetically smaller label
wins.
Your implementation
Edit solution.py and keep this function signature:
You may import NumPy as np. The dictionaries should contain ordinary Python
integers and floats. Do not modify an input, print, or ask for input.