Command Palette

Search for a command to run...

Hectal
Phase 8: Retrieval Basics (RAG)
LLM Engineering · Exercise 3 of 6 PreviousNext
Intermediate

Cosine similarity and top-k

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

Write top_k(query, items, k): items is a list of (name, vector) pairs. Return the names of the k most similar items, best first. Round each score to 4 decimals before comparing, break ties alphabetically by name, and leave out items whose score is 0.

What Check tests

  1. Identical vectors have cosine 1
  2. Vectors with nothing in common have cosine 0
  3. A zero vector gives 0.0, not an error
  4. Ties are ordered by name and zero scores are left out
  5. k limits the result, and the tie still follows name order
  6. The best match comes first

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.