将Networkx图的边相乘的算法 [英] Algorithm to multiply edges of a Networkx graph
本文介绍了将Networkx图的边相乘的算法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以我的问题是在用Networkx库实现的图中找到从一个节点到另一个节点(或同一节点)的最长路径.
So my problem is to find the longest path from a node to another node (or the same node) in a graph implemented with Networkx library.
我不想增加边缘的权重,而要乘以最大的结果.显然,每个节点仅传递一次或根本不传递.
I don't want to add the edges' weights but multiply them and take the biggest result. Obviously, passing only once by each node or not at all.
例如,如果我要从节点1转到节点4,则最佳结果将是:2 x 14 x 34 x 58
For example if I want to go from node 1 to node 4, the best result would be : 2 x 14 x 34 x 58
谢谢您的帮助!
推荐答案
这可能有效:
import networkx as nx
G = nx.Graph()
# create the graph
G.add_edge(1, 2, weight=2 )
G.add_edge(1, 4, weight=5 )
G.add_edge(2, 3, weight=14 )
G.add_edge(2, 4, weight=5 )
G.add_edge(2, 5, weight=4 )
G.add_edge(3, 5, weight=34 )
G.add_edge(4, 5, weight=58 )
start = 1 # start node
end = 4 # end node
all_paths = [path for path in nx.all_simple_paths(G, start, end)]
# initialize result
largest_path = None
largest_path_weight = None
# iterate through all paths to find the largest
for p in all_paths: # keep track of each path
for _ in range(len(p)): # for each node in this path
pairs = zip(p, p[1:]) # get sequence of nodes
product = 1 # reset product for this paths calculation
for pair in pairs: # for each pair of nodes in this path
an_edge = G.get_edge_data(pair[0], pair[1]) # get this edge's data
product *= an_edge['weight'] # multiply all weights
if product > largest_path_weight: # check if this path's product is greater
largest_path = p # if True, set largest to this path
largest_path_weight = product # save the weight of this path
# display result
print 'largest path:', largest_path
print 'weight:', largest_path_weight
对于此示例:
largest path: [1, 2, 3, 5, 4]
weight: 55216
这篇关于将Networkx图的边相乘的算法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文