Python: closest coordinate?

前端 未结 2 882
遇见更好的自我
遇见更好的自我 2020-12-07 04:27

I need help with a function that returns coordinate from a list of coordinates, that\'s closest to some point. For example: closest((9, 2), {(0, 0), (10, 0), (10, 10)}

2条回答
  •  既然无缘
    2020-12-07 04:53

    from math import sqrt
    
    def euqli_dist(p, q, squared=False):
        # Calculates the euclidean distance, the "ordinary" distance between two
        # points
        # 
        # The standard Euclidean distance can be squared in order to place
        # progressively greater weight on objects that are farther apart. This
        # frequently used in optimization problems in which distances only have
        # to be compared.
        if squared:
            return ((p[0] - q[0]) ** 2) + ((p[1] - q[1]) ** 2)
        else:
            return sqrt(((p[0] - q[0]) ** 2) + ((p[1] - q[1]) ** 2))
    
    def closest(cur_pos, positions):
        low_dist = float('inf')
        closest_pos = None
        for pos in positions:
            dist = euqli_dist(cur_pos,pos)
            if dist < low_dist:
                low_dist = dist
                closest_pos = pos
        return closest_pos
    
    print closest((9, 2), {(0, 0), (10, 0), (10, 10)})
    

    Output:

    (10, 0)
    

    If my math is not wrong. ;)

    I'm using this formula

提交回复
热议问题