Skip to content

Commit 43b53f7

Browse files
authored
Merge pull request TheAlgorithms#97 from OmkarPathak/added_programs
Added Stack implementation and some traditional Stack problems
2 parents ab42e3a + ef01688 commit 43b53f7

File tree

7 files changed

+343
-0
lines changed

7 files changed

+343
-0
lines changed

‎data_structures/Graph/Graph.py‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
# Author: OMKAR PATHAK
2+
3+
# We can use Python's dictionary for constructing the graph
4+
5+
classAdjacencyList(object):
6+
def__init__(self):
7+
self.List={}
8+
9+
defaddEdge(self, fromVertex, toVertex):
10+
# check if vertex is already present
11+
iffromVertexinself.List.keys():
12+
self.List[fromVertex].append(toVertex)
13+
else:
14+
self.List[fromVertex] = [toVertex]
15+
16+
defprintList(self):
17+
foriinself.List:
18+
print(i,'->',' -> '.join([str(j) forjinself.List[i]]))
19+
20+
if__name__=='__main__':
21+
al=AdjacencyList()
22+
al.addEdge(0, 1)
23+
al.addEdge(0, 4)
24+
al.addEdge(4, 1)
25+
al.addEdge(4, 3)
26+
al.addEdge(1, 0)
27+
al.addEdge(1, 4)
28+
al.addEdge(1, 3)
29+
al.addEdge(1, 2)
30+
al.addEdge(2, 3)
31+
al.addEdge(3, 4)
32+
33+
al.printList()
34+
35+
# OUTPUT:
36+
# 0 -> 1 -> 4
37+
# 1 -> 0 -> 4 -> 3 -> 2
38+
# 2 -> 3
39+
# 3 -> 4
40+
# 4 -> 1 -> 3
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
# Author: OMKAR PATHAK
2+
3+
classGraph():
4+
def__init__(self):
5+
self.vertex={}
6+
7+
# for printing the Graph vertexes
8+
defprintGraph(self):
9+
foriinself.vertex.keys():
10+
print(i,' -> ', ' -> '.join([str(j) forjinself.vertex[i]]))
11+
12+
# for adding the edge beween two vertexes
13+
defaddEdge(self, fromVertex, toVertex):
14+
# check if vertex is already present,
15+
iffromVertexinself.vertex.keys():
16+
self.vertex[fromVertex].append(toVertex)
17+
else:
18+
# else make a new vertex
19+
self.vertex[fromVertex] = [toVertex]
20+
21+
defBFS(self, startVertex):
22+
# Take a list for stoting already visited vertexes
23+
visited= [False] *len(self.vertex)
24+
25+
# create a list to store all the vertexes for BFS
26+
queue= []
27+
28+
# mark the source node as visited and enqueue it
29+
visited[startVertex] =True
30+
queue.append(startVertex)
31+
32+
whilequeue:
33+
startVertex=queue.pop(0)
34+
print(startVertex, end=' ')
35+
36+
# mark all adjacent nodes as visited and print them
37+
foriinself.vertex[startVertex]:
38+
ifvisited[i] ==False:
39+
queue.append(i)
40+
visited[i] =True
41+
42+
if__name__=='__main__':
43+
g=Graph()
44+
g.addEdge(0, 1)
45+
g.addEdge(0, 2)
46+
g.addEdge(1, 2)
47+
g.addEdge(2, 0)
48+
g.addEdge(2, 3)
49+
g.addEdge(3, 3)
50+
51+
g.printGraph()
52+
print('BFS:')
53+
g.BFS(2)
54+
55+
# OUTPUT:
56+
# 0 -> 1 -> 2
57+
# 1 -> 2
58+
# 2 -> 0 -> 3
59+
# 3 -> 3
60+
# BFS:
61+
# 2 0 3 1
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
# Author: OMKAR PATHAK
2+
3+
classGraph():
4+
def__init__(self):
5+
self.vertex={}
6+
7+
# for printing the Graph vertexes
8+
defprintGraph(self):
9+
print(self.vertex)
10+
foriinself.vertex.keys():
11+
print(i,' -> ', ' -> '.join([str(j) forjinself.vertex[i]]))
12+
13+
# for adding the edge beween two vertexes
14+
defaddEdge(self, fromVertex, toVertex):
15+
# check if vertex is already present,
16+
iffromVertexinself.vertex.keys():
17+
self.vertex[fromVertex].append(toVertex)
18+
else:
19+
# else make a new vertex
20+
self.vertex[fromVertex] = [toVertex]
21+
22+
defDFS(self):
23+
# visited array for storing already visited nodes
24+
visited= [False] *len(self.vertex)
25+
26+
# call the recursive helper function
27+
foriinrange(len(self.vertex)):
28+
ifvisited[i] ==False:
29+
self.DFSRec(i, visited)
30+
31+
defDFSRec(self, startVertex, visited):
32+
# mark start vertex as visited
33+
visited[startVertex] =True
34+
35+
print(startVertex, end=' ')
36+
37+
# Recur for all the vertexes that are adjacent to this node
38+
foriinself.vertex.keys():
39+
ifvisited[i] ==False:
40+
self.DFSRec(i, visited)
41+
42+
if__name__=='__main__':
43+
g=Graph()
44+
g.addEdge(0, 1)
45+
g.addEdge(0, 2)
46+
g.addEdge(1, 2)
47+
g.addEdge(2, 0)
48+
g.addEdge(2, 3)
49+
g.addEdge(3, 3)
50+
51+
g.printGraph()
52+
print('DFS:')
53+
g.DFS()
54+
55+
# OUTPUT:
56+
# 0 -> 1 -> 2
57+
# 1 -> 2
58+
# 2 -> 0 -> 3
59+
# 3 -> 3
60+
# DFS:
61+
# 0 1 2 3
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
# Author: OMKAR PATHAK
2+
3+
importStack
4+
5+
defparseParenthesis(string):
6+
balanced=1
7+
index=0
8+
myStack=Stack.Stack(len(string))
9+
while (index<len(string)) and (balanced==1):
10+
check=string[index]
11+
ifcheck=='(':
12+
myStack.push(check)
13+
else:
14+
ifmyStack.isEmpty():
15+
balanced=0
16+
else:
17+
myStack.pop()
18+
index+=1
19+
20+
ifbalanced==1andmyStack.isEmpty():
21+
returnTrue
22+
else:
23+
returnFalse
24+
25+
if__name__=='__main__':
26+
print(parseParenthesis('((()))')) # True
27+
print(parseParenthesis('((())')) # False
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
# Author: OMKAR PATHAK
2+
3+
importStack
4+
5+
defisOperand(char):
6+
return (ord(char) >=ord('a') andord(char) <=ord('z')) or (ord(char) >=ord('A') andord(char) <=ord('Z'))
7+
8+
defprecedence(char):
9+
ifchar=='+'orchar=='-':
10+
return1
11+
elifchar=='*'orchar=='/':
12+
return2
13+
elifchar=='^':
14+
return3
15+
else:
16+
return-1
17+
18+
definfixToPostfix(myExp, myStack):
19+
postFix= []
20+
foriinrange(len(myExp)):
21+
if (isOperand(myExp[i])):
22+
postFix.append(myExp[i])
23+
elif(myExp[i] =='('):
24+
myStack.push(myExp[i])
25+
elif(myExp[i] ==')'):
26+
topOperator=myStack.pop()
27+
while(notmyStack.isEmpty() andtopOperator!='('):
28+
postFix.append(topOperator)
29+
topOperator=myStack.pop()
30+
else:
31+
while (notmyStack.isEmpty()) and (precedence(myExp[i]) <=precedence(myStack.peek())):
32+
postFix.append(myStack.pop())
33+
myStack.push(myExp[i])
34+
35+
while(notmyStack.isEmpty()):
36+
postFix.append(myStack.pop())
37+
return' '.join(postFix)
38+
39+
if__name__=='__main__':
40+
myExp='a+b*(c^d-e)^(f+g*h)-i'
41+
myExp= [iforiinmyExp]
42+
print('Infix:',' '.join(myExp))
43+
myStack=Stack.Stack(len(myExp))
44+
print('Postfix:',infixToPostfix(myExp, myStack))
45+
46+
# OUTPUT:
47+
# Infix: a + b * ( c ^ d - e ) ^ ( f + g * h ) - i
48+
# Postfix: a b c d ^ e - f g h * + ^ * + i -

‎data_structures/Stacks/Stack.py‎

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
# Author: OMKAR PATHAK
2+
3+
classStack(object):
4+
def__init__(self, limit=10):
5+
self.stack= []
6+
self.limit=limit
7+
8+
# for printing the stack contents
9+
def__str__(self):
10+
return' '.join([str(i) foriinself.stack])
11+
12+
# for pushing an element on to the stack
13+
defpush(self, data):
14+
iflen(self.stack) >=self.limit:
15+
print('Stack Overflow')
16+
else:
17+
self.stack.append(data)
18+
19+
# for popping the uppermost element
20+
defpop(self):
21+
iflen(self.stack) <=0:
22+
return-1
23+
else:
24+
returnself.stack.pop()
25+
26+
# for peeking the top-most element of the stack
27+
defpeek(self):
28+
iflen(self.stack) <=0:
29+
return-1
30+
else:
31+
returnself.stack[len(self.stack) -1]
32+
33+
# to check if stack is empty
34+
defisEmpty(self):
35+
returnself.stack== []
36+
37+
# for checking the size of stack
38+
defsize(self):
39+
returnlen(self.stack)
40+
41+
if__name__=='__main__':
42+
myStack=Stack()
43+
foriinrange(10):
44+
myStack.push(i)
45+
print(myStack)
46+
myStack.pop() # popping the top element
47+
print(myStack)
48+
myStack.peek() # printing the top element
49+
myStack.isEmpty()
50+
myStack.size()

‎sorts/bucket_sort.py‎

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
#!/usr/bin/env python
2+
# Author: OMKAR PATHAK
3+
# This program will illustrate how to implement bucket sort algorithm
4+
5+
# Wikipedia says: Bucket sort, or bin sort, is a sorting algorithm that works by distributing the
6+
# elements of an array into a number of buckets. Each bucket is then sorted individually, either using
7+
# a different sorting algorithm, or by recursively applying the bucket sorting algorithm. It is a
8+
# distribution sort, and is a cousin of radix sort in the most to least significant digit flavour.
9+
# Bucket sort is a generalization of pigeonhole sort. Bucket sort can be implemented with comparisons
10+
# and therefore can also be considered a comparison sort algorithm. The computational complexity estimates
11+
# involve the number of buckets.
12+
13+
# Time Complexity of Solution:
14+
# Best Case O(n); Average Case O(n); Worst Case O(n)
15+
16+
fromP26_InsertionSortimportinsertionSort
17+
importmath
18+
19+
DEFAULT_BUCKET_SIZE=5
20+
21+
defbucketSort(myList, bucketSize=DEFAULT_BUCKET_SIZE):
22+
if(len(myList) ==0):
23+
print('You don\'t have any elements in array!')
24+
25+
minValue=myList[0]
26+
maxValue=myList[0]
27+
28+
# For finding minimum and maximum values
29+
foriinrange(0, len(myList)):
30+
ifmyList[i] <minValue:
31+
minValue=myList[i]
32+
elifmyList[i] >maxValue:
33+
maxValue=myList[i]
34+
35+
# Initialize buckets
36+
bucketCount=math.floor((maxValue-minValue) /bucketSize) +1
37+
buckets= []
38+
foriinrange(0, bucketCount):
39+
buckets.append([])
40+
41+
# For putting values in buckets
42+
foriinrange(0, len(myList)):
43+
buckets[math.floor((myList[i] -minValue) /bucketSize)].append(myList[i])
44+
45+
# Sort buckets and place back into input array
46+
sortedArray= []
47+
foriinrange(0, len(buckets)):
48+
insertionSort(buckets[i])
49+
forjinrange(0, len(buckets[i])):
50+
sortedArray.append(buckets[i][j])
51+
52+
returnsortedArray
53+
54+
if__name__=='__main__':
55+
sortedArray=bucketSort([12, 23, 4, 5, 3, 2, 12, 81, 56, 95])
56+
print(sortedArray)

0 commit comments

Comments
(0)