Python 3.x 尝试使用networkx查找两个节点之间的距离(欧几里德)
关于如何计算图形中两个节点之间的欧几里德距离,有什么建议吗?使用此图表:Python 3.x 尝试使用networkx查找两个节点之间的距离(欧几里德),python-3.x,networkx,graph-theory,Python 3.x,Networkx,Graph Theory,关于如何计算图形中两个节点之间的欧几里德距离,有什么建议吗?使用此图表: nodes = [('B','D'), ('D','E'), ('D','A'), ('E','A'), ('E','C'), ('A','C')] graph = nx.Graph(nodes) nx.draw(graph, node_color = 'red', with_labels = True) 我试过使用 nx.shortest_path(graph, source, target) 使用nx.shorte
nodes = [('B','D'), ('D','E'), ('D','A'), ('E','A'), ('E','C'), ('A','C')]
graph = nx.Graph(nodes)
nx.draw(graph, node_color = 'red', with_labels = True)
我试过使用
nx.shortest_path(graph, source, target)
使用nx.shortest_path()会产生以下错误:
TypeError: argument of type 'NoneType' is not iterable
我知道Dijkstra算法,但我只想计算欧几里德距离。有什么建议吗?您应该可以这样计算最短距离:
dist = nx.shortest_path(graph, 'A', 'B')
dist的长度为您提供节点A和B之间的步数:
len(dist)
# returns 3
计算欧几里德距离需要节点具有某种
与它们相关的坐标
e、 g.存储在属性coords
中:
# adding coordinates:
for n in graph.nodes:
graph.nodes[n]['coords'] = np.random.rand(2)
def get_euclidean_distance(graph, source, dest):
x1, y1 = graph.nodes[source]['coords']
x2, y2 = graph.nodes[dest]['coords']
return np.sqrt((x1-x2)**2 + (y1-y2)**2)
get_euclidean_distance(graph, 'A', 'B')
# out 0.14540849196243125
非常感谢您的回复
len(dist)
将坐标与节点相关联正是我想要的,你所说的欧几里德距离到底是什么意思?