2013-07-10 43 views
0

我試圖在python中遍歷此算法中的圖。如果我想逐個打印所有圖形元素,或者遍歷整個圖形,我應該做些什麼改變? 。在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

你的「圖形」是一本字典,在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。