Distance formula between two points in a list

前端 未结 7 1736
刺人心
刺人心 2021-01-31 19:39

I need to take a list I have created and find the closest two points and print them out. How can I go about comparing each point in the list?

There isn\'t any need to pl

7条回答
  •  粉色の甜心
    2021-01-31 19:55

    Your fixed code. No efficient algorithm, just the brute force one.

    import math # math needed for sqrt
    
    # distance function
    def dist(p1, p2):
        return math.sqrt((p2[0] - p1[0]) ** 2 + (p2[1] - p1[1]) ** 2)
    
    # run through input and reorder in [(x, y), (x,y) ...] format
    input = ["9.5 7.5", "10.2 19.1", "9.7 10.2"] # original input list (entered by spacing the two points)
    points = [map(float, point.split()) for point in input] # final list
    
    # http://en.wikipedia.org/wiki/Closest_pair_of_points
    mindist = float("inf")
    for p1, p2 in itertools.combinations(points, 2):
        if dist(p1, p2) < mindist:
            mindist = dist(p1, p2)
            closestpair = (p1, p2)
    
    print(closestpair)
    

提交回复
热议问题