'How to organise a list of coordinates for closest distance using python?
The body must be 30 characters, you entered 1.
Solution 1:[1]
I'm gonna assume you want to calculate distance from every point to a single point, let's call it my_loc = (0, 0)
Step 1.
Iterate through all the points and calculate their distance using a^2 = b^2 + c^2 pythagorean theorem:
def dist(loc_a, loc_b):
x1, x2 = loc_a[0], loc_b[0]
y1, y2 = loc_a[1], loc_b[1]
z = ((x2-x1) ** 2) + ((y2-y1) ** 2)
return z ** (1/2)
# optionally embrace return value with round(float, decimal_points)
If I got anything wrong here, here's the formula:
where
|AB| is the distance between 2 points, and x and y components are coordinates of a point A and B.
Step 2.
Save all your distances by order to a list, so you will have
points = [(2.8, 9.8), (0.3, 8.3), (4.4, 8.8), (6.8, 7.4), (4.1, 0.3), (4.5, 0.0), (7.6, 1.1), (5.0, 8.2), (7.7, 1.8), (3.4, 6.9), (4.8, 3.2), (0.7, 7.9)]
# and distances
distances = [10.192153844992728, 8.305419917138448, 9.838699100999076, 10.04987562112089, 4.110960958218893, 4.5, 7.679192665899196, 9.604165762834375, 7.907591289387686, 7.692203845452875, 5.768882040742383, 7.930952023559341]
where each element of both list shares the same index (assumming all points are valid, that is [x, y])
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
