-
Notifications
You must be signed in to change notification settings - Fork 65
/
Copy pathgraph.py
78 lines (66 loc) · 2.37 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
""" Implementation of Graph Data Structure and Graph Theory Algorithms
in Python
"""
class Graph:
""" Graph data structure Wrapper"""
def __init__(self, graph_dict=None):
""" initialize a graph object
if no dictionary or none is given, an empty dictionary
will be used
:param graph_dict: initial graph setup
"""
if not graph_dict:
graph_dict = {}
self._graph_dict = graph_dict
def is_vertex(self, node):
""" Returns true if node is vertex of graph, otherwise false """
return node in self._graph_dict
def add_vertex(self, node):
""" Adds new vertex to graph. If vertex is already present in graph,
no action will take place.
:param node: new node to be added to graph
"""
if node not in self._graph_dict:
self._graph_dict[node] = []
def add_edge(self, node, neighbour):
""" Adds new directed edge to graph starting from 'node' to 'neighbor'
It will insert node to graph, if the node is not already present
:param node: starting graph vertex
:param neighbour: ending graph vertex
"""
if node not in self._graph_dict:
self.add_vertex(node)
if neighbour not in self._graph_dict:
self.add_vertex(neighbour)
self._graph_dict[node].append(neighbour)
def order(self):
""" Order returns the order of a graph i.e. number of vertices
:returns: returns number of vertices
"""
return len(list(self._graph_dict))
def vertices(self):
""" return list of all vertices in graph """
return list(self._graph_dict)
def neighbours(self, node):
""" returns all vertices of given node
:param node: graph vertex
:returns: all node neighbour vertices
"""
return self._graph_dict[node]
def show_edges(self):
""" show all the graph edges """
for node in self._graph_dict:
for neighbour in self._graph_dict[node]:
print(f"{node} -> {neighbour}")
def main():
""" Operational Function """
g_dict = {
'1': ['2', '3'],
'2': ['3', '1'],
'3': ['1', '2', '4'],
'4': ['3']
}
g_obj = Graph(g_dict)
g_obj.show_edges()
if __name__ == "__main__":
main()