All problems
Top-k Embedding Cosine Ranking
Problem
Score every word in vectors by cosine similarity with query, sort by descending similarity with alphabetical tie-breaking, and return the top k as [word, similarity] pairs.
Return an empty list when k <= 0 or vectors is empty.
Hint
A zero query has no direction, so every similarity is defined as 0.0.
Test cases
case 1
in: [[1,0],{"a":[1,0],"b":[0,1],"c":[1,1],"d":[-1,0]},2]
expected: [["a",1],["c",0.7071067811865475]]
case 2
in: [[1,0],{"a":[1,0],"b":[0,1],"c":[1,1],"d":[-1,0]},0]
expected: []
case 3
in: [[1,0],{"a":[1,0],"b":[0,1],"c":[1,1],"d":[-1,0]},10]
expected: [["a",1],["c",0.7071067811865475],["b",0],["d",-1]]
case 4
in: [[0,0],{"a":[1,0],"b":[0,1],"c":[1,1],"d":[-1,0]},4]
expected: [["a",0],["b",0],["c",0],["d",0]]
case 5
in: [[1,0],{},2]
expected: []
Starter codePython
import math
def embedding_cosine_ranking_topk(query, vectors, k):
# Your code here
pass5 test cases · run your code against them in the editor