Python · Exercise 6 of 6 Previous
Advanced
Capstone piece: top-k retrieval with scores
Write top_k(query, matrix, k). query is a list of numbers, matrix is a list of rows (each the same length). Compute the cosine similarity of the query with every row (the dot product divided by the product of the two lengths; Topic 16.8) and return the best k as a list of (row_index, score) tuples, highest score first, scores rounded to 3 decimals.
Ties go to the lower row index. A row (or query) of all zeros scores 0.0. If k is larger than the number of rows, return every row.
What Check tests
- Best matches first with rounded scores
- Rows are compared by direction, not length
- Ties go to the lower index
- k larger than the number of rows
- A zero row scores 0.0
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.