How would I go to creating a function that takes a list of points(x,y), and returns the two closest points? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
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))

6th Sep 2020, 4:34 AM
Zero-KohaiSenpai
Zero-KohaiSenpai - avatar
4 Answers
+ 9
(Spoiler alert) OK so I wrote a code snippet that seems to work: https://code.sololearn.com/cxVUVhmTE5i0
6th Sep 2020, 9:57 AM
David Ashton
David Ashton - avatar
+ 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.
6th Sep 2020, 6:13 AM
David Ashton
David Ashton - avatar
+ 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.
6th Sep 2020, 4:46 AM
David Ashton
David Ashton - avatar
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?
6th Sep 2020, 5:10 AM
Zero-KohaiSenpai
Zero-KohaiSenpai - avatar