Is there already implemented algorithm in Networkx to return paths lengths along with paths?

只愿长相守 提交于 2019-12-08 07:27:32

问题


I am using shortest_simple_paths() that is implemented in Networkx to find k-shortest/best paths between two nodes. shortest simple paths

However, I also need the algorithm to return the path length of the returned path. I will need the path length based on already configured 'weights' and not based on hop counts. I know this is a simple problem and can be implemented very easily, but I couldn't find one that is already implemented and effective.


回答1:


It can be achieved by including len(path) in the for loop from the Examples section of shortest_simple_paths.

G = nx.cycle_graph(7)
paths = list(nx.shortest_simple_paths(G, 0, 3))
print(paths)
[[0, 1, 2, 3], [0, 6, 5, 4, 3]]

Modify the edges from the linked example so the shorter path by "hop counts" has a higher cumulative weight than the longer path.

for u,v in G.edges():
    if (all(i < 4 for i in [u,v])):
        G[u][v]['weight'] = 0.75
    else:
        G[u][v]['weight'] = 0.25

Copy the k_shortest_paths function, again from the link.

from itertools import islice
def k_shortest_paths(G, source, target, k, weight=None):
     return list(islice(nx.shortest_simple_paths(G, source, target, weight=weight), k))

Compare the output of k_shortest_paths when weight='weight' and weight=None:

for path in k_shortest_paths(G, 0, 3, 2, weight='weight'):
    print(path, len(path))
([0, 6, 5, 4, 3], 5)
([0, 1, 2, 3], 4)

for path in k_shortest_paths(G, 0, 3, 2, weight=None):
    print(path, len(path))
([0, 1, 2, 3], 4)
([0, 6, 5, 4, 3], 5)


来源:https://stackoverflow.com/questions/53796346/is-there-already-implemented-algorithm-in-networkx-to-return-paths-lengths-along

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!