25.8k views
4 votes
Write a function get_nearest_farthest that takes in a point of

interest (pt) and a list of points and returns the nearest point
and the farthest point from the point of intest.

1 Answer

3 votes

Final answer:

The function get_nearest_farthest calculates the nearest and farthest points from a point of interest using the Euclidean distance formula and returns them. An example implementation in Python uses list comprehension to calculate distances and the min and max functions to find the nearest and farthest points.

Step-by-step explanation:

The function get_nearest_farthest should calculate the distances between the given point of interest (pt) and a list of points and then identify the nearest and farthest points. To achieve this, you can use the Euclidean distance formula. Here's an example of how you might write such a function in Python:

def get_nearest_farthest(pt, points):
distances = [(point, ((pt[0] - point[0])**2 + (pt[1] - point[1])**2)**0.5) for point in points]
nearest = min(distances, key=lambda x: x[1])[0]
farthest = max(distances, key=lambda x: x[1])[0]
return nearest, farthest

This function creates a list of tuples, each containing a point and its distance to pt, then it finds the tuple with the smallest distance and the tuple with the largest distance, returning the corresponding points as the nearest and farthest, respectively.

User LaurentY
by
7.5k points