Command Palette

Search for a command to run...

Hectal
Phase 16: Python in the AI Era
Python · Exercise 3 of 6 PreviousNext
Intermediate

Retrieve the top-k most similar vectors

Write top_k(query, vectors, k). query is a list of numbers, vectors is a list of lists. Return the indices of the k vectors with the highest cosine similarity to the query, best first.

Cosine similarity is the dot product of two vectors divided by the product of their lengths (Topic 16.8). Equal scores are ordered by lower index. A zero vector (all numbers 0) has similarity 0.0, so do not divide by zero. If k is larger than the number of vectors, return all indices.

What Check tests

  1. Ranks by cosine similarity
  2. Ignores vector length
  3. Ties go to the lower index
  4. A zero vector scores 0.0 and does not crash
  5. k larger than the data returns every index

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.