0

From an API i got a "list of lists" containing different coordinates:

List = [[1.0, 2.5, 3.6], [2.02, 2.3, 3.1], [1.5, 6.5, 3.9]]

I have to find the minimum distance between two coordinates. I did something like:

MinDist = 9999999999.
for Coord1 in List:
    for Coord2 in List:
        if Coord1 != Coord2:
            Dist = CalcDistance(Coord1,Coord2)
            if Dist < MinDist:
                MinDist=Dist

Is there a more "intelligent" (and faster) way to get this information?

Ghilas BELHADJ
  • 13,412
  • 10
  • 59
  • 99

2 Answers2

1

Assuming CalcDistance is something like the below, you could use min and a key function together with itertools.combinations

from itertools import zip_longest, combinations

def CalcDistance(a, b):
    return (sum((x-y)**2 for x, y in zip_longest(a, b, fillvalue=0)))**.5

List = [[1.0, 2.5, 3.6], [2.02, 2.3, 3.1], [1.5, 6.5, 3.9]]

print(min(combinations(List, 2), key=lambda x: CalcDistance(*x)))
# ([1.0, 2.5, 3.6], [2.02, 2.3, 3.1])
Patrick Haugh
  • 59,226
  • 13
  • 88
  • 96
0

Why not use a built in algorithm:

import numpy as np
from scipy.spatial.distance import pdist, squareform

List = [[1.0, 2.5, 3.6], [2.02, 2.3, 3.1], [1.5, 6.5, 3.9]]

dist_mat = squareform(pdist(List, CalcDistance))
np.fill_diagonal(dist_mat,np.inf)
i,j = np.unravel_index(dist_mat.argmin(), dist_mat.shape)

print((List[i],List[j]))

The code above combines Find the index of the min value in a pdist condensed distance matrix and Numpy minimum in (row, column) format

Dan
  • 45,079
  • 17
  • 88
  • 157