PIXELBANKv9.1.0
Menu

Euclidean Distance Matrix

Compute the pairwise Euclidean distance matrix for a set of points.

Given nn points in dd-dimensional space, compute the n×nn \times n matrix where entry (i,j)(i, j) is:

d(xi,xj)=∑k=1d(xi,k−xj,k)2d(x_i, x_j) = \sqrt{\sum_{k=1}^{d} (x_{i,k} - x_{j,k})^2}

The diagonal should be all zeros (distance from a point to itself).

Return the matrix with values rounded to 4 decimal places.

Example:

Input:
X = [[0, 0], [3, 0], [0, 4]]
Output:
[[0.0, 3.0, 4.0], [3.0, 0.0, 5.0], [4.0, 5.0, 0.0]]
Reasoning:
  • The input X=[[0,0],[3,0],[0,4]]X = [[0, 0], [3, 0], [0, 4]] represents 3 points in 2-dimensional space.
  • We calculate the pairwise Euclidean distance between each point using the formula: d(xi,xj)=∑k=1d(xi,k−xj,k)2d(x_i, x_j) = \sqrt{\sum_{k=1}^{d} (x_{i,k} - x_{j,k})^2}. For example, the distance between the first and second points is d(x1,x2)=(0−3)2+(0−0)2=9=3.0d(x_1, x_2) = \sqrt{(0-3)^2 + (0-0)^2} = \sqrt{9} = 3.0.
  • We apply this calculation to all pairs of points, resulting in the following distances:
    • d(x1,x3)=(0−0)2+(0−4)2=16=4.0d(x_1, x_3) = \sqrt{(0-0)^2 + (0-4)^2} = \sqrt{16} = 4.0,
    • d(x2,x3)=(3−0)2+(0−4)2=9+16=25=5.0d(x_2, x_3) = \sqrt{(3-0)^2 + (0-4)^2} = \sqrt{9+16} = \sqrt{25} = 5.0.
  • The final output is the n×nn \times n matrix with these distances, rounded to 4 decimal places: [[0.0,3.0,4.0],[3.0,0.0,5.0],[4.0,5.0,0.0]][[0.0, 3.0, 4.0], [3.0, 0.0, 5.0], [4.0, 5.0, 0.0]].

Constraints:

  • X: 2D list (n points x d features)
  • Return n x n symmetric distance matrix
  • Round each value to 4 decimal places
solution.py

Test Results

0/0
Run code to see test results.
Euclidean Distance Matrix - Easy | PixelBank