networkx - networkx: 直径给 13 想找到那些节点或距离是什么
问题描述
我想找到最远的节点。我使用了直径,它给了我一个整数值,我应该怎么做才能在直径的起点和终点获得这些点?即通过使用一些函数在图中找到最远的点。
解决方案
nx.diameter
似乎只是找到节点之间最长最短路径的距离,并且 (docs) 模块中的任何内置函数似乎networkx.algorithms.distance_measures
都无法计算您真正要查找的内容。要获得最远的节点,一种选择是使用一系列调用来调用nx.single_source_shortest_path_length(G,n)
哪里G
是图和n
源节点。n
这将返回从节点到所有节点的最短路径的长度,G
作为由节点键入的字典,值是从节点到源节点的距离n
。然后,您可以查看这些 dicts 以找出哪些节点对具有最长的长度。像这样的东西应该工作。
def get_furthest_nodes(G):
sp_length = {} # dict containing shortest path distances for each pair of nodes
diameter = None # will contain the graphs diameter (length of longest shortest path)
furthest_node_list = [] # will contain list of tuple of nodes with shortest path equal to diameter
for node in G.nodes:
# Get the shortest path from node to all other nodes
sp_length[node] = nx.single_source_shortest_path_length(G,node)
longest_path = max(sp_length[node].values()) # get length of furthest node from node
# Update diameter when necessary (on first iteration and when we find a longer one)
if diameter == None:
diameter = longest_path # set the first diameter
# update the list of tuples of furthest nodes if we have a best diameter
if longest_path >= diameter:
diameter = longest_path
# a list of tuples containing
# the current node and the nodes furthest from it
node_longest_paths = [(node,other_node)
for other_node in sp_length[node].keys()
if sp_length[node][other_node] == longest_path]
if longest_path > diameter:
# This is better than the previous diameter
# so replace the list of tuples of diameter nodes with this nodes
# tuple of furthest nodes
furthest_node_list = node_longest_paths
else: # this is equal to the current diameter
# add this nodes tuple of furthest nodes to the current list
furthest_node_list = furthest_node_list + node_longest_paths
# return the diameter,
# all pairs of nodes with shortest path length equal to the diameter
# the dict of all-node shortest paths
return({'diameter':diameter,
'furthest_node_list':furthest_node_list,
'node_shortest_path_dicts':sp_length})
请注意,此解决方案假定图形是连接的(有向图是强连接的),您应该是这样,因为您使用nx.diameter
. 这应该具有与对直径的调用类似的运行时间,因为该函数执行类似的步骤,它只是不保留导致直径的所有路径链接和节点。请注意,furthest_node_list
返回字典中的项目将使每对节点在相反方向上两次(如果节点a
和b
最短路径等于直径,则两者都(a,b)
将(b,a)
在列表中)。
推荐阅读
- c++ - 从 QTreeView 连接信号/插槽时出现问题
- ios - 我的 AppDelegate Swift 类在一个 Objective-C 文件中被识别,但在 main.m 中却没有。我该如何解决?
- wordpress - WordPress + Vimeo API | 通过 URI 查找特定视频
- django - Django 中的 Jsonresponse 在浏览器中工作,但不在 PostMan 或 Angular 中
- python - 在 selenium 下启动的浏览器不使用插件
- c# - Unity - www.isDone 总是返回 false
- casbin - 如何基于多组成员身份使用 Casbin 保护资源
- postgresql - 如何通知 pod(s) 其他副本 pod 的 IP 地址
- python - 如何在另一个文件夹中导入 Python 模块,而无需相对导入和编辑 PYTHONPATH
- python - 如何将列表:numpy.int64 实例转换为 model.fit 的(稀疏/二进制)分类格式?