Home > Back-end >  Find the closest and the farthest points (2D) between a given point and a list of points in python
Find the closest and the farthest points (2D) between a given point and a list of points in python

Time:05-20

So I am trying to write a python function that can take any given point say (1,2) we can call this a point of interest and then take a list of points say [(6,2), (4,5), (3,4),...] the function should return the points (from the list) that are closest and farthest to our point of interest.

The function should accept two parameters:

    1. Point of interest i.e. pos=(1,2)
    2. List of points i.e. ptlist=[(1,3),(6,2), (4,5), (3,4)]

Also the function should return answers in a form of ((1,3),(4,5)) i.e (closest,farthest)

Here is my code, so far this works but it returns the numpy arrays, while I want my answers to be tuples. I have tried different ways and whatever I try I can't seem to get it right. Maybe we could use something else apart from numpy just so that we get answers in a form of ((1,3),(4,5)).

Here is the code I've written so far:

pos=(1,2)
ptlist=[(2, 6), (8,6), (5,8), (2,4)]
def get_nearest_farthest(pt, ptlist):
    pt=np.array(pt)
    ptlist=np.array(ptlist)
    dist=np.linalg.norm(ptlist-pt, axis=1)
    min_index = np.argmin(dist)
    #tuple(map(tuple,ptlist[min_index])) #Error
    max_index = np.argmax(dist)
    #tuple(map(tuple,ptlist[max_index])) #Error
    return ptlist[min_index],ptlist[max_index]

get_nearest_farthest(pt, ptlist)

CodePudding user response:

You don't need numpy for this. All you need is min() / max() with a key parameter:

distance_metric = lambda x: abs(x[0] - pos[0])**2   abs(x[1] - pos[1])**2
closest = min(ptlist, key=distance_metric)
farthest = max(ptlist, key=distance_metric)

print(closest, farthest)

This outputs:

(2, 4) (8, 6)

CodePudding user response:

This will get you there without using numpy and is pretty efficient with only a single distance calculation per point in your list.

def get_nearest_farthest(pos, pt_list):
    nearest_pt, farthest_pt = None, None
    nearest_d, farthest_d = None, None

    for pt in pt_list:
        d = (pos[0]-pt[0])**2   (pos[1]-pt[1])**2

        if nearest_d is None or d < nearest_d:
            nearest_d = d
            nearest_pt = pt

        if farthest_d is None or d > farthest_d:
            farthest_d = d
            farthest_pt = pt

    return nearest_pt, farthest_pt

pos = (1,2)
pt_list = [(2, 6), (8,6), (5,8), (2,4)]
get_nearest_farthest(pos, pt_list)
  • Related