PY-75

Select Neighbors and Break Voting Ties

  • Medium–Hard
  • Nearest Neighbors
  • Python

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:

  • indices is a new integer NumPy array of the selected reference indices;
  • neighbor_labels is a tuple of their labels in selection order;
  • counts maps each label appearing among those neighbors to its number of appearances;
  • distance_totals maps the same labels to the sum of their selected distances;
  • label is the final voted label.

Apply these rules in order:

  1. Select the k smallest distances. Equal distances are ordered by the smaller original index, so selection is stable.
  2. Find the labels with the largest count among the selected neighbors.
  3. If several labels remain, keep the label with the smallest distance_totals value.
  4. 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.