Neural Mastery
← Practice
Vectorized Euclidean Distance Matrix via Gram Matrixeasy

Vectorized Euclidean Distance Matrix via Gram Matrix

easy NumPy & Data Wrangling 10–15 min

NumPy allowed · plain Python earns 10 bonus points

Linear algebra step 1/4

A vector transforms

Matrix multiplication is the first computation behind every model.
Open lesson →
01vector
02matrix
03transform
04result
[2, −1] × [[1, 2], [−.5, 1]] = [0, −2]

Computed matrix × vector transformation

Compute the complete pairwise Euclidean distance matrix between two feature sets.

Task

Implement pairwise_euclidean_distance(x, y): given matrices x (N x D) and y (M x D), compute the (N, M) matrix of L2 Euclidean distances sqrt(sum((x_i - y_j)**2)). Round each float to 4 decimal places.

Function Signature

pairwise_euclidean_distance(x: list[list[float]], y: list[list[float]]) -> list[list[float]]

Examples

Example 1: 3-4-5 right triangle points
Input: x = [[0, 0]] y = [[3, 4]]
Output: [[5]]
Example 2: Identical points zero distance
Input: x = [[1, 2]] y = [[1, 2], [4, 6]]
Output: [[0, 5]]

Constraints

  • x has shape N x D, y has shape M x D
  • D >= 1
Python3Saved ✓
import math

def pairwise_euclidean_distance(x: list[list[float]], y: list[list[float]]) -> list[list[float]]:
"""Compute N x M Euclidean distance matrix between vectors in x and y.
Round each float to 4 decimal places.
"""
pass

Case 1: 3-4-5 right triangle points
Input: x = [[0, 0]] y = [[3, 4]]
Expected: [[5]]
Case 2: Identical points zero distance
Input: x = [[1, 2]] y = [[1, 2], [4, 6]]
Expected: [[0, 5]]