Calculate distance from one point to all others

前端 未结 3 528
予麋鹿
予麋鹿 2021-01-15 09:34

I am working with a list of ID, X, and Y data for fire hydrant locations. I am trying to find the three closest fire hydrants for each fire hydrant in the list.

a =

3条回答
  •  有刺的猬
    2021-01-15 10:28

    Here you go. Let's say you have an input list with this format [[ID, X, Y],[ID, X, Y]].

    You can simply loop through each hydrant when looping through each hydrant and calculate the min distance between them. You just need to have some variable to store the min distance for each hydrant and the ID of the closest hydrant.

    import math # for sqrt calculation
    
    
    def distance(p0, p1):
        """ Calculate the distance between two hydrant """
        return math.sqrt((p0[1] - p1[1])**2 + (p0[2] - p1[2])**2)
    
    
    input = [[0, 1, 2], [1, 2, -3], [2, -3, 5]] # your input list of hydrant
    
    for current_hydrant in input:  # loop through each hydrant
        min_distance = 999999999999999999999999
        closest_hydrant = 0
        for other_hydrant in input:  # loop through each other hydrant
            if current_hydrant != other_hydrant:
                curr_distance = distance(current_hydrant, other_hydrant) # call the distance function
                if curr_distance < min_distance: # find the closet hydrant
                    min_distance = curr_distance
                    closest_hydrant = other_hydrant[0]
        print("Closest fire hydrants to the", current_hydrant[0], "is the hydrants",
              closest_hydrant, "with the distance of", min_distance)  # print the closet hydrant
    

    Since the distance function is not very complicated i rewrite it, you can use some other function in scipy or numpy library to get the distance.

    Hope this can help ;)

提交回复
热议问题