The shortest distance between one point and a group of others?

I have a problem. I want to write a function in python that will get the X coordinate and group of coordinates S. I need to return the nearest coordinate to x from group s. Therefore, when you call a function, it returns this:

closest((9, 2), {(0, 0), (10, 0), (10, 10)}) # calling a function
(10, 0) 

Because it is closest to both points. I already have a function that calculates the distance between two points

def distance(s,t):
    v = 0
    for i in range(len(t)):
        v = v+(s[i]-t[i])**2
    return (sqrt(v))

But now I am fixated on how to return the nearest tuple of coordinates to the one given in x. My English is not so good, so if you do not understand my question, say so, and I will try to somehow explain.

+4
source share
2 answers

distance,

import math
def distance(p1, p2):
    return math.sqrt((p2[0] - p1[0])**2 + (p2[1] - p1[1])**2)

closest min key distance others

def closest(pt, others):
    return min(others, key = lambda i: distance(pt, i))

>>> closest((9, 2), {(0, 0), (10, 0), (10, 10)})
(10, 0)

def avgDistance(pt, others):
    dists = [distance(pt, i) for i in others]
    return sum(dists) / len(dists)

>>> avgDistance((9, 2), {(0, 0), (10, 0), (10, 10)})
6.505956727697075
+4

. python (scipy), , , , python, C/fortran.

>>> import numpy as np
>>> from scipy.spatial.distance import cdist
>>> a = np.array([[9, 2]])
>>> others = np.array([[0, 0], [10, 0], [10, 10]])
>>> def closest_point(pt, others):
...     distances = cdist(pt, others)
...     return others[distances.argmin()]
... 
>>> closest_point(a, others)
array([10,  0])

:

>>> distances = cdist(a, others)
>>> distances
array([[ 9.21954446,  2.23606798,  8.06225775]])
>>> distances.mean()
6.5059567276970753

, , " ", , , :

>>> all_nodes = np.array([[0,0], [10,0], [0,10], [10, 10], [5,4]])
>>> from scipy.spatial.distance import pdist, squareform
>>> avg_dists = squareform(pdist(all_nodes)).mean(axis=1)
>>> avg_dists
array([ 8.10905197,  8.10905197,  8.39047706,  8.39047706,  5.68534957])
>>> all_nodes[avg_dists.argmin()]
array([5, 4])
+2

All Articles