Home > OS >  Function for finding closest point when giving a starting point, followed by a list
Function for finding closest point when giving a starting point, followed by a list

Time:04-02

I've got my list of points:

((2.8, 9.8), (0.3, 8.3), (4.4, 8.8), (6.8, 7.4), (4.1, 0.3), (4.5, 0.0), 
 (7.6, 1.1), (5.0, 8.2), (7.7, 1.8), (3.4, 6.9), (4.8, 3.2), (0.7, 7.9))

and can't seem to get this to work

def distance(p1, p2) :
    return math.sqrt((p2[0] - p1[0])**2   (p2[1] - p1[1])**2)

def find_closest(start_point, remaining_points) :
    for i in remaining_points:
        distance(start_point,remaining_points(1[0(1)])
    return closest_point

An error just comes up: unsupported operand type(s) for -: 'tuple' and 'float'

any help is appreciated.

CodePudding user response:

@hiroprotagonist's answer will do the job, but here is an answer closer from what you tried.

def distance(p1, p2):
    return math.sqrt((p2[0] - p1[0]) ** 2   (p2[1] - p1[1]) ** 2)


def find_closest(start_point, remaining_points):
    closest_point = remaining_points[0]
    for p in remaining_points:
        dist = distance(start_point, p)
        closest_point = p if dist < distance(start_point, closest_point) else closest_point

    return closest_point


points = ((2.8, 9.8), [(0.3, 8.3), (4.4, 8.8), (6.8, 7.4), (4.1, 0.3), (4.5, 0.0), (7.6, 1.1), (5.0, 8.2), (7.7, 1.8), (3.4, 6.9), (4.8,3.2), (0.7, 7.9)])

print(find_closest(points[0], points[1]))

CodePudding user response:

you could use math.dist and min to do just that:

from math import dist

points = ((2.8, 9.8), (0.3, 8.3), (4.4, 8.8), (6.8, 7.4), (4.1, 0.3), (4.5, 0.0), 
          (7.6, 1.1), (5.0, 8.2), (7.7, 1.8), (3.4, 6.9), (4.8, 3.2), (0.7, 7.9))

def find_closest(start_point, remaining_points):
    return min(remaining_points, key=lambda point: dist(point, start_point))

ret = find_closest(start_point=(3.4, 6.8), remaining_points=points)
  • Related