Exact cosine top-k retrieval
Problem
Return the indices of the k items with the highest cosine similarity to query, in descending order of similarity, with ties broken by lower index. Items with zero norm are never returned. If fewer than k valid items exist, return all valid ones. A zero-norm query raises ValueError.
Signature
def cosine_top_k(query, items, k: int) -> list[int]: ...Examples
The visible tests, as an interactive Python session would show them: each call and the value it should give.
>>> cosine_top_k([1.0, 0.0], [[1.0, 0.0],[0.0, 1.0],[2.0, 0.1]], 2) == [0, 2]
True
>>> cosine_top_k([1.0, 1.0], [[1.0, 1.0],[2.0, 2.0],[1.0, 0.0]], 2) == [0, 1]
TrueHints
Normalise the vectors once, then vectorised dot products.
Use argpartition for the k highest scores, then sort them descending (ties -> lower index).
Zero-norm items are never returned; a zero-norm query raises ValueError.
Reference solution
import numpy as np
def cosine_top_k(query, items, k):
q = np.asarray(query, float); M = np.asarray(items, float)
qn = np.linalg.norm(q)
if qn == 0:
raise ValueError("zero query")
sims = []
for i, v in enumerate(M):
n = np.linalg.norm(v)
if n == 0:
continue
sims.append((-(v @ q) / (n * qn), i))
sims.sort()
return [i for _, i in sims[:k]]What a strong solution covers
- Normalises once and computes vectorised dot products.
argpartitionfor O(n) selection, then sorts k.- Handles zero vectors.
- Discusses ANN indexes (HNSW, IVF-PQ), the recall/latency trade-off, and pre-normalised storage.
Common mistakes
- dividing by zero for zero vectors
- a full sort when k ≪ n (discussion).