BasicsEmbeddingsNumPyOpenAIAnthropicGoogle
Problem
Implement l2_normalize(v) that scales a 1D embedding vector v to unit Euclidean length (∥v∥2=1). If v is the all-zeros vector (∥v∥2=0), return a zero array of the same shape.
Why It Matters: Vector databases (FAISS, pgvector, Pinecone) pre-normalize embeddings to unit length so cosine similarity simplifies to a fast raw dot product.
Function Signature
import numpy as np
def l2_normalize(v) -> np.ndarray:
"""Scale a 1D vector to unit L2 norm."""
Sample Input & Output
Example 1: 3-4-5 Right Triangle Vector
Input:
v = [3.0, 4.0]
Expected Output:
array([0.6, 0.8])
Explanation: L2 norm is 32+42=5.0, so dividing yields [3/5, 4/5] = [0.6, 0.8] with norm 1.0.
Example 2: All-Zeros Guard
Input:
v = [0.0, 0.0, 0.0]
Expected Output:
array([0.0, 0.0, 0.0])
Explanation: Guarding against norm == 0.0 prevents NaN from division by zero.
Constraints & Edge Cases
- Return a 1D float NumPy array of unit L2 norm (or zeros for zero vector).
- Return a float
np.ndarrayof the same shape asv. - Handle Python lists or NumPy arrays seamlessly via
np.asarray(v, dtype=float).
Constraints & Evaluation Criteria
- Return a 1D float NumPy array of unit L2 norm (or zeros for zero vector).
Hints
Learn the Concept First
Two-Stage RAG Reranking: Cross-Encoders & MMR Diversity Selection
Generative AI · Visual Chapter
Diffusion Models Explained: DDPM Forward Noising, Reverse Denoising & CFG
Generative AI · Visual Chapter
Modern Image/Video Gen: Straight-Line Flow Matching & Diffusion Transformers (DiT)
Generative AI · Visual Chapter
Python 3⌘/Ctrl+Enter to Run · ⌘/Ctrl+Shift+Enter to Submit
Loading Code Editor...
+1 Hidden Submit Case
Input / Scenario
[3.0, 4.0]
Expected Output / Criteria
[0.6, 0.8]