easy +10 pts

Cosine Similarity of Vectors

Compute cosine similarity using pure Python arithmetic.

Write a function `cosine_similarity(a, b)` that takes two lists of numbers (or any iterable of numbers) of equal length and returns their cosine similarity as a float. Cosine similarity is defined as the dot product of the two vectors divided by the product of their Euclidean norms. If either vector has zero norm, return `0.0` to avoid division by zero. Use only standard Python; do not import any external libraries. The result should be a Python float. Round the result to 12 decimal places to avoid floating-point noise (e.g., `round(result, 12)`).

Constraints

The two input sequences have equal length. Length is between 1 and 10^5. Elements are integers or floats. Values can be negative. The result is in [-1, 1], except zero-norm cases return 0.0. The solution must run in O(n) time and O(1) extra space.

Example

>>> cosine_similarity([1, 2, 3], [1, 2, 3])
1.0
>>> cosine_similarity([1, 0], [0, 1])
0.0
>>> cosine_similarity([1, -1], [-1, 1])
-1.0
>>> cosine_similarity([0, 0], [5, 5])
0.0
10 points ~15 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Compute the dot product, sum of squares of a, and sum of squares of b in a single loop.
The Euclidean norm is the square root of the sum of squares.
Check if either norm is zero before dividing.
Use round(result, 12) to match expected values exactly.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.