-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgraph.py
369 lines (288 loc) · 10.1 KB
/
graph.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
"""
Graph module for directed graph.
Includes the functions implemented in the Jan 21/22
lectures with one key difference.
The way the nodes and edges are stored has already
been converted to the "adjacency list" representation
we will discuss next lecture.
More specifically, _alist is a dictionary that maps
a node u to the list of neighbours of u. You can call
the methods of the graph in exactly the same way as before,
these changes simply improve the running time.
All running time statements are under the assumption that it takes
O(1) time to index a dictionary.
We will add more to this file in the next lecture, but this
is enough to do the next exercise.
"""
class Graph:
def __init__(self, V=set(), E=[]):
"""
Create a graph with a given set of
vertices and list of edges.
For the purpose of this class
We want E to be a list of tuples.
If no arguements are passed in,
the graph is an empty graph with
no vertices and edges.
Running time: O(len(V) + len(E))
>>> g = Graph()
>>> g._alist == {}
True
>>> g = Graph({1,2,3}, {(1,2), (2,3)})
>>> g._alist.keys() == set({1,2,3})
True
>>> g._alist[1]
[2]
>>> g._alist[3]
[]
"""
# _alist is a dictionary that maps vertices to a list of vertices
# i.e. _alist[v] is the list of neighbours of v
# This also means _alist.keys() is the set of nodes in the graph
self._alist = {}
for v in V:
self.add_vertex(v)
for e in E:
self.add_edge(e)
def add_vertex(self, v):
"""
Adds a vertex to our graph.
Running time: O(1)
>>> g = Graph()
>>> g.add_vertex(1)
>>> 1 in g._alist.keys()
True
>>> g.add_vertex(1)
>>> len(g._alist) == 1
True
"""
if v not in self._alist.keys():
self._alist[v] = []
def add_edge(self, e):
"""
Adds an edge to our graph.
Do not add edge if the vertices
for it do not exist.
Can add more than one copy of an edge.
Running time: O(1)
>>> g = Graph({1,2})
>>> 2 in g._alist[1]
False
>>> g.add_edge((1,2))
>>> 2 in g._alist[1]
True
>>> g.add_edge((1,2))
>>> len(g._alist[1]) == 2
True
"""
if e[0] in self._alist.keys() and e[1] in self._alist.keys():
self._alist[e[0]].append(e[1])
def neighbours(self, v):
"""
Given a vertex v, return a copy of the list
of neighbours of v in the graph.
>>> g = Graph()
>>> g.neighbours(1)
[]
>>> g = Graph({1,2,3}, [(1,2), (1,3)])
>>> g.neighbours(1)
[2, 3]
Running time: O(len(self._alist[v]))
(linear in the number of neighbours of v)
"""
if v not in self._alist.keys():
return []
else:
return list(self._alist[v])
def vertices(self):
"""
Returns a copy of the set of vertices in the graph.
Running time: O(# vertices)
>>> g = Graph({1,2,3}, [(1,2), (2,3)])
>>> g.vertices() == {1,2,3}
True
"""
return list(self._alist.keys())
def edges(self):
"""
Create and return a list of the edges in the graph.
Running time: O(# nodes + # edges)
>>> g = Graph({1,2,3}, [(1,2), (2,3)])
>>> g.edges()
[(1, 2), (2, 3)]
"""
edges = []
for v, adj in self._alist.items():
for u in adj:
edges.append((v, u))
return edges
def is_vertex(self, v):
"""
Returns true if and only if v is a vertex in the graph.
This is more efficient then checking v in g.vertices().
Running time: O(1)
>>> g = Graph({1,2})
>>> g.is_vertex(1)
True
>>> g.is_vertex(3)
False
"""
return v in self._alist.keys()
def is_edge(self, e):
"""
Returns true if and only if e is an edge in the graph.
Running time: O(len(self._alist[e[0]]))
linear in the number neighbours of e[0]
>>> g = Graph({1,2}, [(1,2)])
>>> g.is_edge((1,2))
True
>>> g.is_edge((2,1))
False
>>> g.is_edge((3,1))
False
"""
if not self.is_vertex(e[0]):
return False
return e[1] in self._alist[e[0]]
def is_walk(g, walk):
"""
g is a graph and w is a list of nodes.
Returns true if and only if w is a walk in g.
Running time - O(d * m) where:
- k = len(walk)
- d = maximum size of a neighbourhood of a node
In particular, if the graph has no repeated edges, then d <= # nodes.
>>> g = Graph({1,2,3,4}, [(1,2), (2,3), (2,4), (4,3), (3,1)])
>>> is_walk(g, [1,2,3,1,2,4])
True
>>> is_walk(g, [1,2,3,2])
False
>>> is_walk(g, [])
False
>>> is_walk(g, [1])
True
>>> is_walk(g, [5])
False
"""
for v in walk: # O(k)
if not g.is_vertex(v): # O(1)
return False
if len(walk) == 0:
return False
# Note, can reduce the running time of the entire function
# to O(k) if we implement the method is_edge to run in O(1) time.
# This is a good exercise to think about.
for node in range(0, len(walk) - 1): # O(k)
if not g.is_edge((walk[node], walk[node + 1])): # O(d)
return False
return True
def is_path(g, path):
"""
Returns true if and only if path is a path in g
Running time: O(k*d)
Specifically, is O(k) + running time of is_walk.
>>> g = Graph({1,2,3,4}, [(1,2), (2,3), (2,4), (4,3), (3,1)])
>>> is_path(g, [1,2,3,1,2,4])
False
>>> is_path(g, [1,2,3])
True
"""
return is_walk(g, path) and len(path) == len(set(path))
def search(g, v):
"""
Find all nodes that can be reached from v in the graph g.
Returns a dictionary 'reached' such that reached.keys()
are all nodes that can be reached from v and reached[u]
is the predecessor of u in the search.
Running time: O(# nodes + # edges)
More specifically, O(# edges (u,w) with u reachable from v)
>>> g = Graph({1,2,3,4,5,6}, [(1,2), (1,3), (2,5), (3,2), (4,3), (4,5), (4,6), (5,2), (5,6)])
>>> reached = search(g, 1)
>>> reached.keys() == {1,2,3,5,6}
True
>>> g.is_edge((reached[6], 6))
True
"""
reached = {}
stack = [(v, v)]
# brief running time analysis:
# each edge (u,v) will be added and removed from the stack at most once
while stack:
u, w = stack.pop()
# the block under the if statement will be run at
# most once per node u and the
# inner loop takes time O(# neighbours of u)
# the sum of (# neighbours of u) over all u is just # edges.
if u not in reached.keys():
reached[u] = w
for x in g.neighbours(u):
stack.append((x, u))
# so, even though there are nested loops the running
# time will still be linear
return reached
# from eClass
def least_cost_path(graph, start, dest, cost):
"""
Using Dijkstra's algorithm to solve for the least
cost path in graph from start vertex to dest vertex.
Input variable cost is a function with method signature
c = cost(e) where e is an edge from graph.
>>> graph = Graph({1,2,3,4,5,6}, [(1,2), (1,3), (1,6), (2,1), (2,3), (2,4), (3,1), (3,2), \
(3,4), (3,6), (4,2), (4,3), (4,5), (5,4), (5,6), (6,1), (6,3), (6,5)])
>>> weights = {(1,2): 7, (1,3):9, (1,6):14, (2,1):7, (2,3):10, (2,4):15, (3,1):9, \
(3,2):10, (3,4):11, (3,6):2, (4,2):15, (4,3):11, (4,5):6, (5,4):6, (5,6):9, (6,1):14,\
(6,3):2, (6,5):9}
>>> cost = lambda e: weights.get(e, float("inf"))
>>> least_cost_path(graph, 1,5, cost)
[1, 3, 6, 5]
"""
# est_min_cost[v] is our estimate of the lowest cost
# from vertex start to vertex v
est_min_cost = {}
# parents[v] is the parent of v in our current
# shorest path from start to v
parents = {}
# todo is the set of vertices in our graph which
# we have seen but haven't processed yet. This is
# the list of vertices we have left "to do"
todo = {start}
est_min_cost[start] = 0
while todo:
current = min(todo, key=lambda x: est_min_cost[x])
if current == dest:
return reconstruct_path(start, dest, parents)
todo.remove(current)
for neighbour in graph.neighbours(current):
#if neighbour isn't in est_min_cost, that means I haven't seen it before,
#which means I should add it to my todo list and initialize my lowest
#estimated cost and set it's parent
if not neighbour in est_min_cost:
todo.add(neighbour)
est_min_cost[neighbour] = (est_min_cost[current] + cost((current, neighbour)))
parents[neighbour] = current
elif est_min_cost[neighbour] > (est_min_cost[current] + cost((current, neighbour))):
#If my neighbour isn't new, then I should check if my previous lowest cost path
#is worse than a path going through vertex current. If it is, I will update
#my cost and record current as my new parent.
est_min_cost[neighbour] = (est_min_cost[current] + cost((current, neighbour)))
parents[neighbour] = current
return []
# from eClass
def reconstruct_path(start, dest, parents):
"""
reconstruct_path reconstructs the shortest path from vertex
start to vertex dest.
"parents" is a dictionary which maps each vertex to their
respective parent in the lowest cost path from start to that
vertex.
>>> parents = {'l': ' ', 'e': 'l', 'a': 'e', 'h':'a'}
>>> reconstruct_path('l', 'h', parents)
['l', 'e', 'a', 'h']
"""
current = dest
path = [dest]
while current != start:
path.append(parents[current])
current = parents[current]
path.reverse()
return path