Cosine Similarity

~15 mincode completion

Implement cosine_similarity(u, v) that returns the cosine similarity between two 1D vectors.

Examples

Identical vectors: similarity = 1.0

Input
cosine_similarity([1, 0], [1, 0])
Output
1

Orthogonal vectors: similarity = 0.0

Input
cosine_similarity([1, 0], [0, 1])
Output
0

Parallel vectors (not unit): similarity = 1.0

Input
cosine_similarity([1, 1], [3, 3])
Output
1

Hints

Hint 1

gives the magnitude in one call; pick the axis deliberately.

Hint 2

Do not forget to divide by norms. That step is easy to skip.

Requirements

  • u: 1D NumPy array

  • v: 1D NumPy array of the same length

  • Return Scalar cosine similarity in [-1, 1].

Constraints

  • Allowed library: NumPy only

  • Time limit: 200 ms, Memory: 64 MB

Where this shows up

~15 min

8 employers weight this skill

4 quant funds, 2 defense companies, 2 autonomy companies. Top match scores 93.

Python
import numpy as np

def cosine_similarity(u: np.ndarray, v: np.ndarray) -> float:
    """
    Compute cosine similarity between vectors u and v.

    Args:
        u: 1D NumPy array
        v: 1D NumPy array of the same length

    Returns:
        Scalar cosine similarity in [-1, 1].
    """
    # YOUR CODE HERE
    pass
Loading docs…

The AI Mentor needs an account

It reads your code and the failing tests and nudges you toward the fix without handing you the answer. Free accounts get it on every problem you're working on today.