Skip to content
DeepForgeby svx
All problems
MediumNLPnlp-342

Cosine Similarity Sparse Counts

Problem

Treat each token list as a sparse count vector over its vocabulary and compute the cosine similarity dot(A, B) / (||A|| ||B||), returning 0.0 when either norm is zero.

Given the two token lists, return the similarity.

Hint

Only shared tokens contribute to the dot product.

Test cases

case 1
in: [["a","b"],["a","b"]]
expected: 0.9999999999999998
case 2
in: [["a"],["b"]]
expected: 0
case 3
in: [[],["x"]]
expected: 0
Starter codePython
def cosine_similarity_sparse_counts(tokens_a, tokens_b):
    # Your code here
    pass

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