CODING CHALLENGE · N°05

Cosine Similarity

Easy AI EngineeringEmbeddingsMath

The measure behind every embedding search and RAG system: how aligned are two vectors, regardless of their length? It is the dot product divided by both magnitudes — 1 means identical direction, 0 orthogonal, -1 opposite.

The problem

Given two equal-length vectors a and b, return their cosine similarity: dot(a, b) / (‖a‖ · ‖b‖), where ‖v‖ is the Euclidean norm (square root of the sum of squares). The result lies in [-1, 1] and ignores vector length — only direction matters.

EXAMPLE 1
Input a = [1, 2, 3], b = [1, 2, 3]
Output 1.0
same direction
EXAMPLE 2
Input a = [1, 0], b = [0, 1]
Output 0.0
orthogonal
EXAMPLE 3
Input a = [1, 0], b = [-1, 0]
Output -1.0
opposite
EXAMPLE 4
Input a = [1, 1], b = [2, 2]
Output 1.0
length does not matter
CONSTRAINTS
  • len(a) == len(b) ≥ 1, and neither vector is all zeros.
  • Result in [-1, 1], within floating-point tolerance.
  • Cosine ignores magnitude — scaling a vector does not change the answer.
SOLVE IT YOURSELF

Your turn — write it

Edit the stub, hit Run (or ⌘/Ctrl + Enter), and watch the hidden tests. Stuck? the hints are right above and Reveal solution is one click away.

YOUR TASK

Implement cosine_similarity(a, b) = dot product of a and b, divided by the product of their Euclidean norms.

HINTS — 4 IDEAS
  1. The dot product is the sum of element-wise products: Σ aᵢ·bᵢ.
  2. The Euclidean norm of v is sqrt(Σ vᵢ²).
  3. Divide the dot product by ‖a‖ · ‖b‖ to cancel out length and leave only direction.
  4. Identical vectors give 1; orthogonal give 0; opposite give -1.
CPython · WebAssembly