Classes are your friend. This is a bit more work, but it's nicer, and it's extensible.
class point:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return '{0}, {1}'.format(self.x, self.y)
def distanceto(self, other):
return math.sqrt( (self.x - other.x)**2 + (self.y - other.y)**2)
def closestpoint(self, pointlist):
pointinfo = [{'point':x, 'dist':self.distanceto(x)} for x in pointlist]
pointinfo.sort(key=lambda p: p.dist)
return pointinfo[0]
Instead of reading points from a file and saving the X
and Y
components seperately, why not save them as a list of points?
# all points read from the file.
listofpoints = []
for i in range(0, 10):
listofpoints.append(point(data.X[i], data.Y[i]))
# the point you'd like to test against.
mytestpoint = point(0,0)
You can just test the difference of all the points now, using the point member methods.
closest = mytestpoint.closestpoint(listofpoints)
print 'Closest point is at {0} and is a distance of {1} from {2}'.format(
closest,
mytestpoint.distanceto(closest),
mytestpoint)