-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgraph.py
286 lines (225 loc) · 8.68 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
"""
File: graph.py
"""
from abstractcollection import AbstractCollection
class LinkedEdge(object):
# An edge has a source vertex, a destination vertex,
# a weight, and a mark attribute.
def __init__(self, fromVertex, toVertex, weight = None):
self._vertex1 = fromVertex
self._vertex2 = toVertex
self._weight = weight
self._mark = False
def clearMark(self):
"""Clears the mark on the edge."""
self._mark = False
def __eq__(self, other):
"""Two edges are equal if they connect
the same vertices."""
if self is other: return True
if type(self) != type(other):
return False
return self._vertex1 == other._vertex1 and \
self._vertex2 == other._vertex2
def getOtherVertex(self, thisVertex):
"""Returns the vertex opposite thisVertex."""
if thisVertex == None or thisVertex == self._vertex2:
return self._vertex1
else:
return self._vertex2
def getToVertex(self):
"""Returns the edge's destination vertex."""
return self._vertex2
def getWeight(self):
"""Returns the edge's weight."""
return self._weight
def isMarked(self):
"""Returns True if the edge is marked
or False otherwise."""
return self._mark
def setMark(self):
"""Sets the mark on the edge."""
self._mark = True
def setWeight(self, weight):
"""Sets the weight on the edge to weight."""
self._weight = weight
def __str__(self):
"""Returns the string representation of the edge."""
return str(self._vertex1) + ">" + \
str(self._vertex2) + ":" + \
str(self._weight)
class LinkedVertex(object):
# A vertex has a label, a list of incident edges,
# and a mark attribute.
def __init__(self, label):
self._label = label
self._edgeList = list()
self._mark = False
def clearMark(self):
"""Clears the mark on the vertex."""
self._mark = False
def getLabel(self):
"""Returns the label of the vertex."""
return self._label
def isMarked(self):
"""Returns True if the vertex is marked
or False otherwise."""
return self._mark
def setLabel(self, label, g):
"""Sets the vertex's label to label."""
g._vertices.pop(self._label, None)
g._vertices[label] = self
self._label = label
def setMark(self):
"""Sets the mark on the vertex."""
self._mark = True
def __str__(self):
"""Returns the string representation of the vertex."""
return str(self._label)
def __eq__(self, other):
"""Two vertices are equal if they have
the same labels."""
if self is other: return True
if type(self) != type(other): return False
return self.getLabel() == other.getLabel()
# Methods used by LinkedGraph
def addEdgeTo(self, toVertex, weight):
"""Connects the vertices with an edge."""
edge = LinkedEdge(self, toVertex, weight)
self._edgeList.append(edge)
def getEdgeTo(self, toVertex):
"""Returns the connecting edge if it exists, or
None otherwise."""
edge = LinkedEdge(self, toVertex)
try:
return self._edgeList[self._edgeList.index(edge)]
except:
return None
def incidentEdges(self):
"""Returns the incident edges of this vertex."""
return iter(self._edgeList)
def neighboringVertices(self):
"""Returns the neighboring vertices of this vertex."""
vertices = list()
for edge in self._edgeList:
vertices.append(edge.getOtherVertex(self))
return iter(vertices)
def removeEdgeTo(self, toVertex):
"""Returns True if the edge exists and is removed,
or False otherwise."""
edge = LinkedEdge(self, toVertex)
if edge in self._edgeList:
self._edgeList.remove(edge)
return True
else:
return False
class LinkedDirectedGraph(AbstractCollection):
# A graph has a count of vertices, a count of edges,
# and a dictionary of label/vertex pairs.
def __init__(self, sourceCollection = None):
self._edgeCount = 0
self._vertices = {}
AbstractCollection.__init__(self, sourceCollection)
# Methods for clearing, marks, sizes, string rep
def clear(self):
"""Clears the graph."""
self._size = 0
self._edgeCount = 0
self._vertices = {}
def clearEdgeMarks(self):
"""Clears all the edge marks."""
for edge in self.edges():
edge.clearMark()
def clearVertexMarks(self):
"""Clears all the vertex marks."""
for vertex in self.vertices():
vertex.clearMark()
def sizeEdges(self):
"""Returns the number of edges."""
return self._edgeCount
def sizeVertices(self):
"""Returns the number of vertices."""
return len(self)
def __str__(self):
"""Returns the string representation of the graph."""
result = str(self.sizeVertices()) + " Vertices: "
for vertex in self._vertices:
result += " " + str(vertex)
result += "\n";
result += str(self.sizeEdges()) + " Edges: "
for edge in self.edges():
result += " " + str(edge)
return result
def add(self, label):
"""For compatibility with other collections."""
self.addVertex(label)
# Vertex related methods
def addVertex(self, label):
"""Adds a vertex with the given label to the graph."""
self._vertices[label] = LinkedVertex(label)
self._size += 1
def containsVertex (self, label):
return label in self._vertices
def getVertex(self, label):
return self._vertices[label]
def removeVertex(self, label):
"""Returns True if the vertex was removed, or False otherwise."""
removedVertex = self._vertices.pop(label, None)
if removedVertex is None:
return False
# Examine all other vertices to remove edges
# directed at the removed vertex
for vertex in self.vertices():
if vertex.removeEdgeTo(removedVertex):
self._edgeCount -= 1
# Examine all edges from the removed vertex to others
for edge in removedVertex.incidentEdges():
self._edgeCount -= 1
self._size -= 1
return True
# Methods related to edges
def addEdge(self, fromLabel, toLabel, weight):
"""Connects the vertices with an edge with the given weight."""
fromVertex = self.getVertex(fromLabel)
toVertex = self.getVertex(toLabel)
fromVertex.addEdgeTo(toVertex, weight)
self._edgeCount += 1
def containsEdge(self, fromLabel, toLabel):
"""Returns True if an edge connects the vertices,
or False otherwise."""
return self.getEdge(fromLabel, toLabel) != None
def getEdge(self, fromLabel, toLabel):
"""Returns the edge connecting the two vertices, or None if
no edge exists."""
fromVertex = self.getVertex(fromLabel)
toVertex = self.getVertex(toLabel)
return fromVertex.getEdgeTo(toVertex)
def removeEdge(self, fromLabel, toLabel):
"""Returns True if the edge was removed, or False otherwise."""
fromVertex = self.getVertex(fromLabel)
toVertex = self.getVertex(toLabel)
edgeRemovedFlg = fromVertex.removeEdgeTo(toVertex)
if edgeRemovedFlg:
self._edgeCount -= 1
return edgeRemovedFlg
# Iterators
def __iter__(self):
"""Supports iteration over a view of self (the vertices)."""
return self.vertices()
def edges(self):
"""Supports iteration over the edges in the graph."""
result = list()
for vertex in self.vertices():
result += list(vertex.incidentEdges())
return iter(result)
def vertices(self):
"""Supports iteration over the vertices in the graph."""
return iter(self._vertices.values())
def incidentEdges(self, label):
"""Supports iteration over the incident edges of the
given verrtex."""
return self.getVertex(label).incidentEdges()
def neighboringVertices(self, label):
"""Supports iteration over the neighboring vertices of the
given verrtex."""
return self.getVertex(label).neighboringVertices()