Skip to content
DeepForgeby svx
All problems
MediumNLPnlp-247

Dense Embedding Cosine Rank

Problem

Rank one document by cosine similarity to query among the vectors keyed by id.

Sort documents by descending similarity with alphabetical tie-breaking and return the 1-based rank of target, or -1 when target is absent. A zero-norm query or vector scores 0.0.

Hint

Build the full sorted order first, then locate target in it.

Test cases

case 1
in: [[1,0],{"a":[1,0],"b":[0,1],"c":[1,1]},"c"]
expected: 2
case 2
in: [[1,0],{"a":[1,0],"b":[0,1]},"z"]
expected: -1
case 3
in: [[0,0],{"a":[1,0],"b":[0,1]},"b"]
expected: 2
case 4
in: [[1,1],{"x":[1,1],"y":[1,0]},"y"]
expected: 2
case 5
in: [[1,1],{},"a"]
expected: -1
Starter codePython
import math
def dense_cosine_rank(query, vectors, target):
    # Your code here
    pass

5 test cases · run your code against them in the editor