I have list that has 20 coordinates (x and y coordinates). I can calculate the distance between any two coordinates, but I have a hard time writing an algorithm that will iterate through the list and calculate the distance between the first node and every other node. for example,
ListOfCoordinates = [(1,2), (3,4), (5,6), (7,8), (9,10), (11,12)]
In this case I need a for loop that will interate the list and calculate the distance between the first coordinate and the second coordinates, distance between first coordinate and third coordinate, etc. I am in need of an algorithm to help me out, then I will transform it into a python code. Thanks
Thanks for ll the feedback. It's been helpful.
The math. dist() method returns the Euclidean distance between two points (p and q), where p and q are the coordinates of that point. Note: The two points (p and q) must be of the same dimensions.
You can loop through the list items by using a while loop. Use the len() function to determine the length of the list, then start at 0 and loop your way through the list items by referring to their indexes. Remember to increase the index by 1 after each iteration.
We can iterate through a list by using the range() function and passing the length of the list. It will return the index from 0 till the end of the list. The output would be the same as above.
Whenever you need something combinatorics-oriented ("I need first and second, then first and third, then...") chances are the itertools
module has what you need.
from math import hypot
def distance(p1,p2):
"""Euclidean distance between two points."""
x1,y1 = p1
x2,y2 = p2
return hypot(x2 - x1, y2 - y1)
from itertools import combinations
list_of_coords = [(1,2), (3,4), (5,6), (7,8), (9,10), (11,12)]
[distance(*combo) for combo in combinations(list_of_coords,2)]
Out[29]:
[2.8284271247461903,
5.656854249492381,
8.48528137423857,
11.313708498984761,
14.142135623730951,
2.8284271247461903,
5.656854249492381,
8.48528137423857,
11.313708498984761,
2.8284271247461903,
5.656854249492381,
8.48528137423857,
2.8284271247461903,
5.656854249492381,
2.8284271247461903]
edit: Your question is a bit confusing. Just in case you only want the first point compared against the other points:
from itertools import repeat
pts = [(1,2), (3,4), (5,6), (7,8), (9,10), (11,12)]
[distance(*pair) for pair in zip(repeat(pts[0]),pts[1:])]
Out[32]:
[2.8284271247461903,
5.656854249492381,
8.48528137423857,
11.313708498984761,
14.142135623730951]
But usually in this type of problem you care about all the combinations so I'll leave the first answer up there.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With