import itertools
import networkx as nx
import numpy as np
def path_cost(G, path, attr='weight'):
return sum([G[path[i]][path[i+1]][attr] for i in range(len(path)-1)])
G = ...
cutoff = 3
output = dict()
for source, target in itertools.combinations(list(G.nodes), 2):
minimum_cost = np.inf
for path in nx.simple_paths.shortest_simple_paths(G, source, target, weight='depth'):
if path_cost(G, path, 'depth') > cutoff:
continue # to next source, target pair
else:
if path_cost(G, path, 'weight') < minimum_cost:
output[(source, target)] = path
创建图形时,需要为每条边指定一个表示距离的属性:
计算最短路径时,可以指定该属性,以便计算加权最短路径:
all_pairs_shortest_paths
只计算未加权的情况;但是,如果不指定源节点和目标节点,那么shortest_path
也会计算所有对编辑
networkx中没有任何东西符合要求(AFAIK)。但是,您可以使用
nx.simple_paths.shortest_simple_paths
为按总“深度”排序的两个节点之间的所有路径创建生成器,然后根据权重计算最短路径:相关问题 更多 >
编程相关推荐