我正在尝试找到最大等级节点和深度。这是我的代码。
import pygraphviz as pgv
class Test:
def __init__(self):
self.G = pgv.AGraph(directed=True)
self.G.add_node('a')
self.G.add_node('b')
self.G.add_node('c')
self.G.add_node('d')
self.G.add_node('e')
self.G.add_node('f')
self.G.add_edge('a', 'b')
self.G.add_edge('b', 'c')
self.G.add_edge('b', 'd')
self.G.add_edge('d', 'e')
self.G.add_edge('e', 'f')
print(self.G.string())
self.find_max_rank_node()
def find_max_rank_node(self):
nodes = self.G.nodes()
depth = 0
for n in nodes:
layer1 = self.G.successors(n)
if layer1:
depth = depth + 1
for layer_one in layer1:
layer2 = self.G.successors(layer_one)
print(n, layer2)
if __name__ == '__main__': Test()
输出应为f
和4
。我开始对其进行编码,但是意识到我不会知道分支的深度...而且我不确定如何编写循环。
使用NetworkX Python库中的算法进行图形处理。
使用安装NetworkX pip install networkx
。然后:
import networkx as nx
from networkx.drawing.nx_agraph import from_agraph
import pygraphviz as pgv
# constructing graph with pygraphviz
G = pgv.AGraph(directed=True)
G.add_node('a')
G.add_node('b')
G.add_node('c')
G.add_node('d')
G.add_node('e')
G.add_node('f')
G.add_edge('a', 'b')
G.add_edge('b', 'c')
G.add_edge('b', 'd')
G.add_edge('d', 'e')
G.add_edge('e', 'f')
# converting pygraphviz graph to networkx graph
X = from_agraph(G)
# dictionary {node: length}
lengths = nx.shortest_path_length(X, 'a')
result = max(lengths.items(), key=lambda p: p[1])
结果是('f', 4)
。
因为问题是关于pygraphviz
,所以我提供了将pygraphviz
对象转换为的解决方案networkx
。
您也可以networkx
在软件中仅使用图形,然后再使用转换为pygraphviz
图形networkx.drawing.nx_agraph.to_agraph
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句