Command Palette

Search for a command to run...

Hectal
Phase 2: Embeddings in Depth
RAG and Vector Search · Exercise 2 of 5 PreviousNext
Beginner

Rank vectors by cosine similarity

DOCS maps names to vectors (they do not have to be length 1).

Write cosine(a, b): the dot product divided by both lengths. If either vector has length 0, return 0.0.

Write top_k(query, docs, k) returning a list of (name, score) pairs, best first, at most k of them. Ties keep the order of docs.

What Check tests

  1. cosine ignores vector length
  2. A zero vector scores 0
  3. top_k returns the best first, with scores
  4. Ties keep the order of the documents
  5. k larger than the number of documents is fine

Stuck? One hint at a time

The solution unlocks after your first Check. Try first: that is where the learning happens.

main.py
Sign in to run your code.

Output

Press Run to see what your program prints.