Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # A udemy Python course task
- # Given a list of tuples, holding the x and y coordinates of a series of points,
- # return the 2 tuples of the points which are furthest apart
- def find_farthest_points(pointlist):
- # Initialise an empty list which will contain all our calculation results
- reslist = []
- # pointlist is a list of tuples containing x,y coords of a series of points
- # Here we will use nested loops, to pick up ALL combinations of points,
- # although this will produce some duplicates, and each point will get compared
- # with itself as well as with all other points. but this doesn't matter
- for pos1 in pointlist:
- for pos2 in pointlist:
- # Compute the square of the distance between 2 points
- dsq = (pos1[0] - pos2[0]) ** 2 + (pos1[1] - pos2[1]) ** 2
- # The actual distance is the square root of dsq, but as we are only asked
- # to find which points are farthest apart, and not the actual distance,
- # there is no point in actually computing the square root
- # Now we add the distance-squared and the 2 points, to a results list
- # With dsq as the first item in each list entry, as that's what we will sort on
- reslist.append((dsq, pos1, pos2))
- # Now we have built a list of distance-squared and points.
- # Sort it in reverse sequence, then return the two points from the first entry
- # (which corresponds to the furthest distance)
- sorted_list = sorted(reslist, reverse=True)
- return sorted_list[0][1], sorted_list[0][2]
- pl = [(1, 2), (2, 4), (3, 7), (4, 5)]
- point1, point2 = find_farthest_points(pl)
- print("The furthest apart points are", point1, "and", point2)
- # Output:
- # The furthest apart points are (3, 7) and (1, 2)
Add Comment
Please, Sign In to add comment