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
- Identical vectors have cosine 1
- Vectors with nothing in common have cosine 0
- A zero vector gives
0.0, not an error - Ties are ordered by name and zero scores are left out
- k limits the result, and the tie still follows name order
- 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.