【问题标题】:Finding the closest pair of coordinates/tuples using Python使用 Python 查找最近的坐标/元组对
【发布时间】:2021-09-30 06:01:35
【问题描述】:

我一直在尝试从元组列表中找到两个最近的点/坐标/元组。

例如,如果函数nearest_neighbor() 的输入列表如下所示:

[(1, 2), (4, 5), (5, 5), (4, 1)]

该函数应返回以下内容:

(4, 5), (5, 5)

以下是我的尝试,但不幸的是我无法让它工作。

import numpy as np
A = [(1, 2), (4, 5), (5, 5), (4, 1)]
A = np.array(A)
len = []
for i in range((len(A)):
  leftbottom = np.array(A[i])
  distances = np.linalg.norm(A-leftbottom, axis=1)
  min_index = np.argmin(distances)
  len.append(distances[min_index])

print(f"the closest point is {len.min()}")

【问题讨论】:

  • 我认为您遇到的问题与计算矩阵的 Frobenius 范数无关。目前尚不清楚您要做什么。

标签: python list tuples nearest-neighbor


【解决方案1】:

不使用numpy的解决方案:

from itertools import combinations
import math

A = [(1, 2), (4, 5), (5, 5), (4, 1)]

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

closest_points = None
min_dist = float('inf')

for p1, p2 in combinations(A, 2):
    dist = distance(p1,p2)

    if dist < min_dist:
        closest_points = (p1,p2)
        min_dist = dist

print(f"the closest points are {closest_points}")

【讨论】:

    【解决方案2】:

    正如@Frank Yellin 指出的那样,distances = np.linalg.norm(A-leftbottom, axis=1) 行正在计算 matrix norm,而不是向量范数。即使不使用numpy,您也可以获得问题的解决方案,这是我的 O(n^2) 解决方案:

    def nearest_neighbours(tup):
        smallest_dist = None
        first = None
        second = None
        for i in range(len(tup)-1):
            for j in range(i+1, len(tup)):
                dist = (tup[i][0]-tup[j][0])**2 + (tup[i][1]-tup[j][1])**2
                if smallest_dist is None or dist < smallest_dist:
                    smallest_dist = dist
                    first = tup[i]
                    second = tup[j]
        return first, second
    

    【讨论】:

    • 干净的答案。但由于我的输入是一个元组列表,我得到了“列表”对象不可调用的错误。
    • @Parsh 我在你的输入上测试了我的函数,它没有抛出任何错误,你确定你正确地调用了这个函数吗?我的解决方案从不尝试调用列表...
    【解决方案3】:

    您的代码中有很多错误。首先你将len定义为一个列表,然后尝试调用内置的len函数来计算数组A的长度。另一个问题是,当你计算两点之间的距离时,你必须检查它们是否是相同与否。距离的最小值也不给出两个点,它只返回距离。

    import numpy as np
    A=np.array([(1,2),(4,5),(5,5),(4,1)])
    l=[]
    min_dist=np.linalg.norm(A[0]-A[i])# initialising minimum distance
    closest_pts=(A[0],A[1] )# initialising closest points
    
    for i in range(len(A)):
      pt_i=A[i]
      pts_rest=np.delete(A,i,axis=0)#creates another array without the ith element
      distances=np.linalg.norm(pts_rest-pt_i,axis=1)
      
      if min_dist>min(distances):
        min_index=np.argmin(distances)
        pt_j=pts_rest[min_index]
        closest_pts=(list(pt_i),list(pt_j))
    
    print(f"The closest points are {closest_pts}")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-12-13
      • 1970-01-01
      • 1970-01-01
      • 2019-07-31
      • 2020-03-04
      • 2017-05-29
      • 1970-01-01
      相关资源
      最近更新 更多