一个点与一组点之间的最短距离?

use*_*561 5 python function

我有个问题。我想在python中编写一个函数,该函数将接收坐标X和一组坐标S。我需要从组s返回最接近x的坐标。因此,当您调用函数时,它将返回以下内容:

closest((9, 2), {(0, 0), (10, 0), (10, 10)}) # calling a function
(10, 0) 
Run Code Online (Sandbox Code Playgroud)

因为它最接近两个点。我已经有一个函数可以计算两点之间的距离

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

但是,现在我仍然停留在如何将最接近的坐标元组返回给x中给定的元组中。我的英语不好,所以,如果您不明白我的问题,请说出来,我会尽力解释。

Cor*_*mer 5

首先,您可以创建一个distance仅返回两点之间距离的函数

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

然后closest可以将min函数与key参数一起使用,以将distance函数与参数中的每个元素一起使用others

def closest(pt, others):
    return min(others, key = lambda i: distance(pt, i))
Run Code Online (Sandbox Code Playgroud)

>>> closest((9, 2), {(0, 0), (10, 0), (10, 10)})
(10, 0)
Run Code Online (Sandbox Code Playgroud)

计算平均距离

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
Run Code Online (Sandbox Code Playgroud)


Oli*_* W. 5

不要重新发明轮子。此功能存在于 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])
Run Code Online (Sandbox Code Playgroud)

要计算到该点的所有距离的平均距离:

>>> distances = cdist(a, others)
>>> distances
array([[ 9.21954446,  2.23606798,  8.06225775]])
>>> distances.mean()
6.5059567276970753
Run Code Online (Sandbox Code Playgroud)

最后,为了找到“最中心”的点,即它与所有其他点的平均距离最小,您必须计算所有节点之间的距离:

>>> 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])
Run Code Online (Sandbox Code Playgroud)