- Notifications
You must be signed in to change notification settings - Fork 638
Expand file tree
/
Copy pathP63_Graph.py
More file actions
Latest commit
80 lines (63 loc) · 2.11 KB
/
Copy pathP63_Graph.py
File metadata and controls
80 lines (63 loc) · 2.11 KB
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
# Author: OMKAR PATHAK
# In this example, we will see how to implement graphs in Python
classVertex(object):
''' This class helps to create a Vertex for our graph '''
def__init__(self, key):
self.key=key
self.edges= {}
defaddNeighbour(self, neighbour, weight=0):
self.edges[neighbour] =weight
def__str__(self):
returnstr(self.key) +'connected to: '+str([x.keyforxinself.edges])
defgetEdges(self):
returnself.edges.keys()
defgetKey(self):
returnself.key
defgetWeight(self, neighbour):
try:
returnself.edges[neighbour]
except:
returnNone
classGraph(object):
''' This class helps to create Graph with the help of created vertexes '''
def__init__(self):
self.vertexList= {}
self.count=0
defaddVertex(self, key):
self.count+=1
newVertex=Vertex(key)
self.vertexList[key] =newVertex
returnnewVertex
defgetVertex(self, vertex):
ifvertexinself.vertexList:
returnself.vertexList[vertex]
else:
returnNone
defaddEdge(self, fromEdge, toEdge, cost=0):
iffromEdgenotinself.vertexList:
newVertex=self.addVertex(fromEdge)
iftoEdgenotinself.vertexList:
newVertex=self.addVertex(toEdge)
self.vertexList[fromEdge].addNeighbour(self.vertexList[toEdge], cost)
defgetVertices(self):
returnself.vertexList.keys()
def__iter__(self):
returniter(self.vertexList.values())
if__name__=='__main__':
graph=Graph()
graph.addVertex('A')
graph.addVertex('B')
graph.addVertex('C')
graph.addVertex('D')
graph.addEdge('A', 'B', 5)
graph.addEdge('A', 'C', 6)
graph.addEdge('A', 'D', 2)
graph.addEdge('C', 'D', 3)
forvertexingraph:
forvertexesinvertex.getEdges():
print('({}, {}) => {}'.format(vertex.getKey(), vertexes.getKey(), vertex.getWeight(vertexes)))
# OUTPUT:
# (C, D) => 3
# (A, C) => 6
# (A, D) => 2
# (A, B) => 5