Skip to content

Commit 68f5900

Browse files
author
Sakis Kasampalis
committed
Merge branch 'master' of github.com:faif/python-patterns
2 parents f1528c5 + 2123037 commit 68f5900

File tree

1 file changed

+75
-0
lines changed

1 file changed

+75
-0
lines changed

graph_search.py

+75
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
class GraphSearch:
2+
"""Graph search emulation in python, from source http://www.python.org/doc/essays/graphs/"""
3+
4+
def __init__(self, graph):
5+
self.graph = graph
6+
7+
def find_path(self, start, end, path=[]):
8+
self.start = start
9+
self.end = end
10+
self.path = path
11+
12+
self.path+=[self.start]
13+
if self.start == self.end:
14+
return self.path
15+
if not self.graph.has_key(self.start):
16+
return None
17+
for node in self.graph[self.start]:
18+
if node not in self.path:
19+
newpath = self.find_path(node, self.end, self.path)
20+
if newpath:
21+
return newpath
22+
return None
23+
24+
def find_all_path(self, start, end, path=[]):
25+
self.start = start
26+
self.end = end
27+
self.path = path
28+
self.path+=[self.start]
29+
if self.start == self.end:
30+
return [self.path]
31+
if not self.graph.has_key(self.start):
32+
return []
33+
paths=[]
34+
for node in self.graph[self.start]:
35+
if node not in self.path:
36+
newpaths = self.find_all_path(node, self.end, self.path)
37+
for newpath in newpaths:
38+
paths.append(newpath)
39+
return paths
40+
41+
def find_shortest_path(self, start, end, path=[]):
42+
self.start = start
43+
self.end = end
44+
self.path = path
45+
46+
self.path+=[self.start]
47+
if self.start == self.end:
48+
return self.path
49+
if not self.graph.has_key(self.start):
50+
return None
51+
shortest = None
52+
for node in self.graph[self.start]:
53+
if node not in self.path:
54+
newpath = self.find_shortest_path(node, self.end, self.path)
55+
if newpath:
56+
if not shortest or len(newpath) < len(shortest):
57+
shortest = newpath
58+
return shortest
59+
60+
#example of graph usage
61+
graph = {'A':['B', 'C'],
62+
'B': ['C', 'D'],
63+
'C': ['D'],
64+
'D': ['C'],
65+
'E': ['F'],
66+
'F': ['C']
67+
}
68+
69+
#inistialization of new graph search object
70+
graph1 = GraphSearch(graph)
71+
72+
73+
print graph1.find_path('A', 'D')
74+
print graph1.find_all_path('A', 'D')
75+
print graph1.find_shortest_path('A', 'D')

0 commit comments

Comments
 (0)