acclivity

pyUdemy-FurthestPoints

Apr 14th, 2021 (edited)
239
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.79 KB | None | 0 0
  1. # A udemy Python course task
  2. # Given a list of tuples, holding the x and y coordinates of a series of points,
  3. # return the 2 tuples of the points which are furthest apart
  4.  
  5.  
  6. def find_farthest_points(pointlist):
  7.  
  8.     # Initialise an empty list which will contain all our calculation results
  9.     reslist = []
  10.  
  11.     # pointlist is a list of tuples containing x,y coords of a series of points
  12.     # Here we will use nested loops, to pick up ALL combinations of points,
  13.     # although this will produce some duplicates, and each point will get compared
  14.     # with itself as well as with all other points. but this doesn't matter
  15.  
  16.     for pos1 in pointlist:
  17.         for pos2 in pointlist:
  18.             # Compute the square of the distance between 2 points
  19.  
  20.             dsq = (pos1[0] - pos2[0]) ** 2 + (pos1[1] - pos2[1]) ** 2
  21.  
  22.             # The actual distance is the square root of dsq, but as we are only asked
  23.             # to find which points are farthest apart, and not the actual distance,
  24.             # there is no point in actually computing the square root
  25.  
  26.             # Now we add the distance-squared and the 2 points, to a results list
  27.             # With dsq as the first item in each list entry, as that's what we will sort on
  28.  
  29.             reslist.append((dsq, pos1, pos2))
  30.  
  31.     # Now we have built a list of distance-squared and points.
  32.     # Sort it in reverse sequence, then return the two points from the first entry
  33.     # (which corresponds to the furthest distance)
  34.  
  35.     sorted_list = sorted(reslist, reverse=True)
  36.  
  37.     return sorted_list[0][1], sorted_list[0][2]
  38.  
  39.  
  40. pl = [(1, 2), (2, 4), (3, 7), (4, 5)]
  41.  
  42. point1, point2 = find_farthest_points(pl)
  43.  
  44. print("The furthest apart points are", point1, "and", point2)
  45.  
  46.  
  47. # Output:
  48. # The furthest apart points are (3, 7) and (1, 2)
  49.  
  50.  
Add Comment
Please, Sign In to add comment