Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a more pythonic way to find the point in a list which is closest to another point?

Tags:

python

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]
like image 996
Kristian Avatar asked Nov 25 '10 20:11

Kristian


1 Answers

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

like image 112
SingleNegationElimination Avatar answered Oct 24 '22 02:10

SingleNegationElimination