All problems
Rank Documents by Cosine
Problem
Rank documents against a query using sparse cosine similarity.
query_vec and each entry of doc_vecs are dicts mapping term to weight. Compute cosine similarity as the dot product over shared terms divided by the product of L2 norms, and score 0.0 when either side has zero norm. Return a list of [doc_index, similarity] pairs sorted by similarity descending and then index ascending, including every document.
Hint
Sort with a key of (-similarity, index) to get both tie rules.
Test cases
case 1
in: [{"a":1},[{"a":1},{"b":1}]]
expected: [[0,1],[1,0]]
case 2
in: [{"a":1,"b":1},[{"a":1},{"b":1},{"a":1,"b":1}]]
expected: [[2,1],[0,0.7071067811865475],[1,0.7071067811865475]]
case 3
in: [{"a":1},[]]
expected: []
case 4
in: [{},[{"a":1}]]
expected: [[0,0]]
Starter codePython
import math
def rank_documents(query_vec, doc_vecs):
# Your code here
pass4 test cases · run your code against them in the editor