forked from larissalages/code_problems
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgraph.py
More file actions
40 lines (32 loc) · 785 Bytes
/
graph.py
File metadata and controls
40 lines (32 loc) · 785 Bytes
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
class graph:
def __init__(self, gdict=None):
if gdict is None:
gdict =[]
self.gdict = gdict
def getVertices(self):
return list(self.gdict.keys())
def getEdges(self):
edges = []
for vtx in self.gdict:
for edg in self.gdict[vtx]:
if {vtx, edg} not in edges:
edges.append({vtx, edg})
return edges
def addVertex(self, vxt):
if vxt not in self.gdict:
self.gdict[vxt] = []
def addEdge(self, edge):
v1, v2 = tuple(edge)
if v2 not in self.gdict[v1]:
self.gdict[v1].append(v2)
graph_elements = { "a" : ["b","c"],
"b" : ["a", "d"],
"c" : ["a", "d"],
"d" : ["e"],
"e" : ["d"]
}
g = graph(graph_elements)
g.addVertex('f')
g.addEdge({'a','e'})
print(g.getVertices())
print(g.getEdges())