我试图在python中遍历此算法中的图形。我应该做些什么改变 如果我想逐个打印图形的所有元素或遍历整个图形 曲线图。
非常感谢任何帮助。感谢。
grapth={'A': ['B', 10, 'B', 10, 'B', 10, 'C', 15], 'C': [1001, 'OUT'], 'B':
[1000, 'IN', 1000, 'IN']}
print "Path:",find_all_paths(Portdict1,'A','IN')
def find_all_paths(graph, start, end, path=[]):
path = path + [start]
if start == end:
return [path]
if not graph.has_key(start):
return []
paths = []
for node in graph[start]:
if node not in path:
newpaths = find_all_paths(graph, node, end, path)
for newpath in newpaths:
paths.append(newpath)
return paths
答案 0 :(得分:0)
您的“图表”是字典,Python中的字典是无序的,如果您想使用ordered dictionary,可以从collections
模块中导入。
from collections import OrderedDict
graph = OrderedDict({'A': ['B', 10, 'B', 10, 'B', 10, 'C', 15], 'C': [1001, 'OUT'], 'B': [1000, 'IN', 1000, 'IN']})
证明它是订购的:
>>> for key, value in graph.items():
print key, value
A ['B', 10, 'B', 10, 'B', 10, 'C', 15]
C [1001, 'OUT']
B [1000, 'IN', 1000, 'IN']
请注意,由于您的初始代码具有“A,C,B”顺序中的密钥,这是他们将使用OrderedDict保留的顺序。