I have a list of 2d points, and would like to find the one which is closest to a given point. The code (get_closest_point()) below does what I want. But is there a nicer way to do this in python?
class Circle(object):
def __init__(self, pos):
self.position = pos
class Point(object):
..
def compute_distance_to(self, p)
..
class SomeClient(object):
..
def get_closest_point(self, points, p1):
closest = (None, float(sys.maxint))
for p2 in points:
distance = p2.compute_distance_to(p1)
if distance < closest[1]:
closest = (p2, distance)
return closest[0]
def get_closest_circle(self, circles, p1):
closest = (None, float(sys.maxint))
for c in circles:
distance = c.position.compute_distance_to(p1)
if distance < closest[1]:
closest = (c, distance)
return closest[0]
You can use the key
argument to the min()
function:
Edit: after some consideration, this should be a method of your Point
class, and i'll fix some other obvious deficiencies:
class Point(object):
def get_closest_point(self, points):
return min(points, key=self.compute_distance_to)
or, to do this with a more elaborate case, say a list of instances with a loc
attribute,
min(items, key= lambda item: p1.compute_distance_to(item.loc))
and so on
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With