python寻找距离最近的点_Python最短距离点

Write a function called dist that takes in two points (so two lists of two elements each), and computes the distance between them. Make sure this works on the example below before proceeding to the next step.

Use dist in a nested loop inside shortestDist to compare each element of the list of points with every element in the list after it. So, basically, find the shortest distance between points in a list.

以下是我目前掌握的情况:sample= [[45, -99], [24, 83], [-48, -68], [-97, 99], [-8, -77], [-2, 50], [44, 41], [-48, -58], [-1, 53], [14, 86], [31, 94], [12, -91], [33, 50], [82, 72], [83, -90], [10, 78], [7, -22], [90, -88], [-21, 5], [6, 23]]

def dist(p0, p1):

return (((p0[0] - p1[0])**2) + ((p0[1] - p1[1])**2))**.5

def shortestDist(sample):

distances = []

for i in range(len(sample)-1):

for j in range(i+1, len(sample)):

distances += [dist(sample[i],sample[j])]

return(min(distances))

找到两点之间的距离。我只需要一些帮助,找出如何开始写shortestDist来比较所有点并跟踪最短距离。更新:错误已解决,我现在可以走了。谢谢大家的帮助!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用Dijkstra算法来求解两间的最短路径,以下是Python实现代码: ```python import heapq # 定义图类 class Graph: def __init__(self): self.nodes = set() # 存储节的集合 self.edges = {} # 存储边的字典,键为起,值为终距离的元组列表 self.distances = {} # 存储每个节到起距离 # 添加节 def add_node(self, value): self.nodes.add(value) # 添加有向边 def add_edge(self, from_node, to_node, distance): if from_node not in self.edges: self.edges[from_node] = [] self.edges[from_node].append((to_node, distance)) # 计算最短路径 def dijkstra(self, initial): # 初始化距离 self.distances = {node: float('inf') for node in self.nodes} self.distances[initial] = 0 # 使用堆来优化寻找下一个节的过程 heap = [(0, initial)] while heap: # 弹出堆顶元素,即距离最近的节 (distance, current_node) = heapq.heappop(heap) # 如果当前节已经被处理过,则跳过 if distance > self.distances[current_node]: continue # 遍历当前节的邻居节 for (neighbor, edge_weight) in self.edges[current_node]: # 计算新的距离 new_distance = distance + edge_weight # 如果新的距离比之前计算的距离小,则更新距离 if new_distance < self.distances[neighbor]: self.distances[neighbor] = new_distance # 将邻居节加入堆中 heapq.heappush(heap, (new_distance, neighbor)) # 返回所有节到起的最短距离 return self.distances ``` 使用示例: ```python # 创建图对象 graph = Graph() # 添加节 graph.add_node('A') graph.add_node('B') graph.add_node('C') graph.add_node('D') graph.add_node('E') # 添加边 graph.add_edge('A', 'B', 6) graph.add_edge('A', 'D', 1) graph.add_edge('B', 'C', 5) graph.add_edge('B', 'D', 2) graph.add_edge('B', 'E', 2) graph.add_edge('C', 'E', 5) graph.add_edge('D', 'E', 1) # 计算最短路径 distances = graph.dijkstra('A') # 输出结果 print(distances) ``` 输出结果为: ``` {'A': 0, 'B': 3, 'C': 8, 'D': 1, 'E': 2} ``` 其中,键为节名称,值为到起的最短距离
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值