Back to Practice
#0184

Cosine Similarity Between Vectors

MediumNumPy25 min20 XP

Problem

Given two NumPy vectors a and b, return their cosine similarity. Return 0.0 if either vector has zero norm.

Why This Matters

Cosine similarity is used for embeddings, document similarity, recommendation systems, and retrieval.

Function Signature

def cosine_similarity(a, b):

Examples

Example 1
Inputa = np.array([1, 0]), b = np.array([1, 1])
Output0.7071...

The dot product is 1 and the norms are 1 and sqrt(2).

Constraints

  • Return the exact requested result.
  • Handle common edge cases.
  • Keep the solution readable before optimizing.
CodePython
Visible browser tests run here when available.
Testcases1 visible / 3 hidden categories
Core example
Inputa = np.array([1, 0]), b = np.array([1, 1])
Expected0.7071...

The dot product is 1 and the norms are 1 and sqrt(2).

Hidden Test Categories
minimal inputrepeated valueslarger realistic input