Distance formula between two points in a list

前端 未结 7 1752
刺人心
刺人心 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:57

    This might work:

    oInput = ["9.5 7.5", "10.2 19.1", "9.7 10.2"]
    
    # parse inputs
    inp = [(float(j[0]), float(j[1])) for j in [i.split() for i in oInput]]
    
    # initialize results with a really large value
    min_distance = float('infinity')
    min_pair = None
    
    # loop over inputs
    length = len(inp)
    for i in xrange(length):
        for j in xrange(i+1, length):
            point1 = inp[i]
            point2 = inp[j]
    
            if math.hypot(point1[0] - point2[0], point1[1] - point2[0]) < min_distance:
                min_pair = [point1, point2]
    

    once the loops are done, min_pair should be the pair with the smallest distance.

    Using float() to parse the text leaves room for improvement.

    math.hypot is about a third faster than calculating the distance in a handwritten python-function

提交回复
热议问题