L2 Normalization: Every Row to Length One

Linear AlgebraMedium+20 XP+15

L2 Normalization: Every Row to Length One

Normalizing a vector divides it by its own length, leaving direction intact and magnitude at exactly 1. Do it to every row of a matrix and you get a set of embeddings that can be compared purely by direction.

1normalized_row = row / sqrt(Σ row[i]²)

Task: write normalize_rows(matrix) returning the matrix with each row scaled to unit length, rounded to 4 decimal places.

  • Rows are normalized independently — nothing is shared between them.
  • A row of all zeros has no direction and no length to divide by; return it unchanged as zeros.
  • An empty matrix returns an empty list.

This is what makes cosine similarity cheap. Once every row is unit length, the cosine between two of them is just their dot product — no division left to do, which is exactly how vector databases compare millions of embeddings quickly.

Examples

matrix = [[3.0, 4.0], [1.0, 0.0]]
returns [[0.6, 0.8], [1.0, 0.0]]
matrix = [[1.0, 1.0, 1.0, 1.0]]
returns [[0.5, 0.5, 0.5, 0.5]]

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run