0
How would I go to creating a function that takes a list of points(x,y), and returns the two closest points?
For example if I called the function; closest_points([(1, 2), (4, 5), (5, 5), (4, 1)]) it would return ((4, 5), (5, 5))
4 Réponses
+ 9
(Spoiler alert) OK so I wrote a code snippet that seems to work:
https://code.sololearn.com/cxVUVhmTE5i0
+ 8
I think you would need a function like
def dist_xy(x1, y1, x2, y2):
dist = ((x2-x1)**2+(y2-y1)**2)**.5
return x1, y1, x2, y2, dist
Then run the function on all the combinations of the points and make a list the tuples of 5 returned values for each pair of points.
Then sort the list of tuples by the 5th element of each, i.e. distance, and you will get the shortest distance and the coordinates of the associated two points.
+ 6
I guess you could use the pythagorean equation to calculate the distance between every point and every other point (use itertools.combinations?) and use min() to find the shortest.
0
True that would work for the example I have as it returned (1,2) and (4,1) which I can remove, but would it work for a list of random length of points?