All problems
Cosine Neighbor Similarity
Problem
Compute the cosine similarity between the adjacency rows of nodes u and v in an undirected graph.
For unweighted graphs the dot product is the number of common neighbors and each norm is the square root of the degree, so the score is common / sqrt(deg(u) * deg(v)). Return 0.0 when either node is isolated. edges is a list of [u, v] pairs.
Hint
Cosine similarity normalizes the shared-neighbor count by both degrees.
Test cases
case 1
in: [3,[[0,1],[1,2],[2,0]],0,1]
expected: 0.5
case 2
in: [3,[[0,1],[1,2]],0,1]
expected: 0
case 3
in: [4,[[0,1],[0,2],[0,3]],1,2]
expected: 1
case 4
in: [3,[],0,1]
expected: 0
Starter codePython
import math
def cosine_similarity(n, edges, u, v):
# Your code here
pass4 test cases · run your code against them in the editor