Compute every pairwise distance without a Python loop

Nearest-neighbour search, k-means and retrieval all start the same way: you need the distance from every row of A to every row of B. A double for loop is slow. Broadcasting does it in one shot.

Write pairwise_dist(A, B) where A has shape (n, d) and B has shape (m, d). Return an (n, m) array where entry [i, j] is the Euclidean distance between A[i] and B[j].

Signaturedef pairwise_dist(A, B)

Example

A = [[0, 0]], B = [[3, 4], [0, 1]] gives [[5.0, 1.0]].

Understand the idea

Many algorithms need the distance from every row of A to every row of B. A double loop works but is slow in Python. Broadcasting lets NumPy pair every row of A with every row of B at once, like making a full mileage table between two lists of cities. Add a new axis so A becomes (n, 1, d) and B becomes (1, m, d); their difference is then (n, m, d). Square, sum over d, and take the square root. Worked example: A = [[1, 2]], B = [[4, 6], [1, 2]]. First pair: difference (3, 4), squares 9 + 16 = 25, root 5. Second pair: difference (0, 0), distance 0. Output [[5.0, 0.0]]. Rule: D[i, j] = sqrt(sum over k of (A[i, k] - B[j, k])^2). Forgetting the square root gives squared distances, a common bug. k-nearest neighbours, k-means and vector search all start with this matrix.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 3.

  • Sample 1: examplepairwise_dist([[0, 0]], [[3, 4], [0, 1]])
  • Sample 2: random 5x4pairwise_dist(_A, _B)
  • Test 3: distance to itself is 0pairwise_dist(_A, _A).diagonal()