Cosine similarity sparse vectors
Compute the cosine similarity of two sparse vectors given as dicts mapping index/key to a nonzero numeric weight. Cosine = dot(a,b) / (||a|| * ||b||), where the dot product sums a[k]*b[k] over keys present in both, and each norm is the square root of the sum of squared weights. If either vector has zero norm (empty dict), return 0.0. Return the similarity rounded to 6 decimals.
Implement
sparse_cosine(a: dict, b: dict) → floatExamples
in
[{"x":1,"y":2},{"y":2,"z":1}]out0.8What a strong answer looks like
State your approach and its time/space complexity out loud before you optimize. Handle the edge cases (empty input, duplicates, overflow), and say why you chose this over the brute force. Green tests are the floor, not the grade.
0:00 of about 20 min
solution.py
InputExpectedGot
[{"x":1,"y":2},{"y":2,"z":1}]0.8not run yetsample