Top-k by cosine similarity

mediumEmbeddings~25 min · 7 tests

Every vector database answers one question: which stored vectors point the same way as this one? Build the brute-force version that every index is measured against.

Write top_k(query, docs, k):

  • query is a list of floats.
  • docs is a list of vectors, each the same length as query.
  • Return the indices of the k docs with the highest cosine similarity to query, best first.
  • Break ties by the lower index.
  • A zero vector has similarity 0 with everything (don’t divide by zero).
  • If k is larger than len(docs), return every index.

Cosine similarity is the dot product divided by the product of the lengths:

cos(a, b) = (a · b) / (|a| × |b|)

No numpy. Plain Python only.

>>> top_k([1, 0], [[0, 1], [1, 1], [2, 0]], 2)
[2, 1]
Learn the ideaRead the post →
solution.pyPython 3.14 · Pyodide

Press ⌘ ↵ or Run to check the visible tests. Submit runs the hidden ones too. Everything runs in your browser.

⌘ ↵ to run