PIXELBANKv9.1.0
Menu

Problem Statement

Contrastive training compares embeddings by cosine similarity, which requires them to live on the unit sphere. Implement the L2 normalization applied to every image and text embedding before the dot product.

Background

For a vector v, the L2-normalized version is

v^=v∥v∥2,∥v∥2=∑ivi2\hat{v} = \frac{v}{\lVert v \rVert_2}, \qquad \lVert v \rVert_2 = \sqrt{\sum_i v_i^2}

After this, a dot product between two normalized vectors is their cosine similarity. Guard the zero vector: if the norm is 0, return the vector unchanged (all zeros) rather than dividing by zero.

Your Task

Implement:

def l2_normalize(v):

Return the normalized vector as a list rounded to 4 decimals.

Input Format

  • v: list of numbers.

Output Format

  • A list of floats rounded to 4 decimals.

Sample

print(l2_normalize([3.0, 4.0]))

Output:

[0.6, 0.8]

Example:

Input:
print(l2_normalize([3.0, 4.0]))
Output:
[0.6, 0.8]
Reasoning:
  • Compute the L2 norm of the input vector [3.0,4.0][3.0, 4.0] by taking the square root of the sum of squared elements: ∥v∥2=3.02+4.02=9+16=25=5.0\|v\|_2 = \sqrt{3.0^2 + 4.0^2} = \sqrt{9 + 16} = \sqrt{25} = 5.0.
  • Since the norm is non-zero, divide each component of the vector by this norm to project it onto the unit sphere: 3.0/5.0=0.63.0 / 5.0 = 0.6 and 4.0/5.0=0.84.0 / 5.0 = 0.8.
  • Round each resulting component to 4 decimal places to meet the output format requirements, yielding 0.60.6 and 0.80.8.
  • The final output is [0.6, 0.8]

Constraints:

  • 1 <= len(v) <= 4096.
  • The norm is the Euclidean (L2) norm.
  • A zero vector is returned unchanged (no division by zero).
  • Round every entry to 4 decimals; avoid -0.0.
solution.py

Test Results

0/0
Run code to see test results.