Skip to content

Commit 09af5d4

Browse files
committed
Added Graphs
1 parent bd88cb5 commit 09af5d4

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed

pygorithm/data_structures/graph.py

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
# Author: OMKAR PATHAK
2+
# Created On: 12th August 2017
3+
4+
class AdjacencyList(object):
5+
def __init__(self):
6+
self.graph = {}
7+
self.count = 0
8+
9+
def print_graph(self):
10+
for i in self.graph:
11+
print(i,'->',' -> '.join([str(j) for j in self.graph[i]]))
12+
13+
def add_edge(self, from_vertex, to_vertex):
14+
''' function to add an edge in the graph '''
15+
# check if vertex is already present
16+
if from_vertex in self.graph.keys():
17+
self.graph[from_vertex].append(to_vertex)
18+
self.count += 1
19+
else:
20+
self.graph[from_vertex] = [to_vertex]
21+
self.graph[to_vertex] = []
22+
self.count += 1
23+
24+
def get_code(self):
25+
''' returns the code for the current class '''
26+
import inspect
27+
return inspect.getsource(AdjacencyList)
28+
29+
class TopologicalSort(AdjacencyList):
30+
def topological_sort(self):
31+
visited = [False] * self.count # Marking all vertices as not visited
32+
stack = [] # Stack for storing the vertex
33+
for vertex in range(self.count):
34+
# Call the recursive function only if not visited
35+
if visited[vertex] == False:
36+
self.topological_sort_rec(vertex, visited, stack)
37+
38+
return stack
39+
40+
# Recursive function for topological Sort
41+
def topological_sort_rec(self, vertex, visited, stack):
42+
43+
# Mark the current node in visited
44+
visited[vertex] = True
45+
46+
# mark all adjacent nodes of the current node
47+
try:
48+
for adjacent_node in self.graph[vertex]:
49+
if visited[adjacent_node] == False:
50+
self.topological_sort_rec(adjacent_node, visited, stack)
51+
except KeyError:
52+
return
53+
54+
# Push current vertex to stack which stores the result
55+
stack.insert(0,vertex)
56+
57+
def get_code(self):
58+
''' returns the code for the current class '''
59+
import inspect
60+
return inspect.getsource(TopologicalSort)

0 commit comments

Comments
 (0)