Write cosine_similarity(a, b) returning the cosine of the angle between two vectors as a float: dot(a, b) / (norm(a) * norm(b)). If either vector has zero magnitude, return 0.0 to avoid dividing by zero. Implement it from scratch using only the standard library (the math module) -- no numpy. Standard library only.
from unittest import TestCase
from exercise import cosine_similarity
class Evaluate(TestCase):
def test_identical_vectors_are_one(self):
self.assertAlmostEqual(cosine_similarity([1, 2, 3], [1, 2, 3]), 1.0)
def test_orthogonal_vectors_are_zero(self):
self.assertAlmostEqual(cosine_similarity([1, 0], [0, 1]), 0.0)
def test_opposite_vectors_are_minus_one(self):
self.assertAlmostEqual(cosine_similarity([1, 0], [-1, 0]), -1.0)
def test_zero_vector_guard(self):
self.assertEqual(cosine_similarity([0, 0], [1, 1]), 0.0)
import math
def cosine_similarity(a, b):
dot = sum(x * y for x, y in zip(a, b))
na = math.sqrt(sum(x * x for x in a))
nb = math.sqrt(sum(y * y for y in b))
denom = na * nb
if denom == 0:
return 0.0
return dot / denom