![](/img/trans.png)
[英]How to analyse and identify directed graph relationships (between nodes) in Python
[英]Python: path between nodes in directed graph
一个简单的问题:G是有边的有向图
a->b
a->c
c->d
它存储在Python字典中
G={'a':['b','c'], c:['d']}
我想要a和d之间的路径,d和a之间的路径,b和d之间的路径等。
import collections
import itertools as IT
def find_shortest_path(graph, start, end, path=[]):
path = path + [start]
if start == end:
return path
if start not in graph:
return None
shortest = None
for node in graph[start]:
if node not in path:
newpath = find_shortest_path(graph, node, end, path)
if newpath:
if not shortest or len(newpath) < len(shortest):
shortest = newpath
return shortest
G={'a':['b','c'], 'c':['d']}
for node1, node2 in IT.combinations(list('abcd'), 2):
print('{} -> {}: {}'.format(node1, node2, find_shortest_path(G, node1, node2)))
产量
a -> b: ['a', 'b']
a -> c: ['a', 'c']
a -> d: ['a', 'c', 'd']
b -> c: None
b -> d: None
c -> d: ['c', 'd']
您可能也对networkx , igraph或graph-tool软件包感兴趣。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.