Cosine similarity sparse vectors

Write codeMedium20 minOpenAI and Anthropic style

Your task

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.

Examples

sparse_cosine(a: dict, b: dict) -> float
Example 1
Inputsparse_cosine({"x": 1, "y": 2}, {"y": 2, "z": 1})
Output0.8