[英]Algorithm to multiply edges of a Networkx graph
所以我的問題是在用Networkx庫實現的圖中找到從一個節點到另一個節點(或同一節點)的最長路徑。
我不想增加邊緣的權重,但要乘以最大的結果。 顯然,每個節點僅傳遞一次或根本不傳遞。
例如,如果我要從節點1轉到節點4,則最佳結果將是: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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.