I tried to traverse a graph in this algorithm in python. What Changes should I make if I want to print all elements of graph one by one or traversing the whole graph.
Any help will be very much appreciated. Thanks.
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
Your "Graph" is a dictionary, dictionaries in Python are unordered, if you want to use an ordered dictionary, you can import it from the collections
module.
from collections import OrderedDict
graph = OrderedDict({'A': ['B', 10, 'B', 10, 'B', 10, 'C', 15], 'C': [1001, 'OUT'], 'B': [1000, 'IN', 1000, 'IN']})
Proof that it is ordered:
>>> 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']
Notice, that since your initial code has the keys in the order "A, C, B" that is the order they will stay in with the OrderedDict.