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

+40
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+
class AdjacencyList(object):
6+
def __init__(self):
7+
self.List = {}
8+
9+
def addEdge(self, fromVertex, toVertex):
10+
# check if vertex is already present
11+
if fromVertex in self.List.keys():
12+
self.List[fromVertex].append(toVertex)
13+
else:
14+
self.List[fromVertex] = [toVertex]
15+
16+
def printList(self):
17+
for i in self.List:
18+
print(i,'->',' -> '.join([str(j) for j in self.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
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
# Author: OMKAR PATHAK
2+
3+
class Graph():
4+
def __init__(self):
5+
self.vertex = {}
6+
7+
# for printing the Graph vertexes
8+
def printGraph(self):
9+
for i in self.vertex.keys():
10+
print(i,' -> ', ' -> '.join([str(j) for j in self.vertex[i]]))
11+
12+
# for adding the edge beween two vertexes
13+
def addEdge(self, fromVertex, toVertex):
14+
# check if vertex is already present,
15+
if fromVertex in self.vertex.keys():
16+
self.vertex[fromVertex].append(toVertex)
17+
else:
18+
# else make a new vertex
19+
self.vertex[fromVertex] = [toVertex]
20+
21+
def BFS(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+
while queue:
33+
startVertex = queue.pop(0)
34+
print(startVertex, end = ' ')
35+
36+
# mark all adjacent nodes as visited and print them
37+
for i in self.vertex[startVertex]:
38+
if visited[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
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
# Author: OMKAR PATHAK
2+
3+
class Graph():
4+
def __init__(self):
5+
self.vertex = {}
6+
7+
# for printing the Graph vertexes
8+
def printGraph(self):
9+
print(self.vertex)
10+
for i in self.vertex.keys():
11+
print(i,' -> ', ' -> '.join([str(j) for j in self.vertex[i]]))
12+
13+
# for adding the edge beween two vertexes
14+
def addEdge(self, fromVertex, toVertex):
15+
# check if vertex is already present,
16+
if fromVertex in self.vertex.keys():
17+
self.vertex[fromVertex].append(toVertex)
18+
else:
19+
# else make a new vertex
20+
self.vertex[fromVertex] = [toVertex]
21+
22+
def DFS(self):
23+
# visited array for storing already visited nodes
24+
visited = [False] * len(self.vertex)
25+
26+
# call the recursive helper function
27+
for i in range(len(self.vertex)):
28+
if visited[i] == False:
29+
self.DFSRec(i, visited)
30+
31+
def DFSRec(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+
for i in self.vertex.keys():
39+
if visited[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
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
# Author: OMKAR PATHAK
2+
3+
import Stack
4+
5+
def parseParenthesis(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+
if check == '(':
12+
myStack.push(check)
13+
else:
14+
if myStack.isEmpty():
15+
balanced = 0
16+
else:
17+
myStack.pop()
18+
index += 1
19+
20+
if balanced == 1 and myStack.isEmpty():
21+
return True
22+
else:
23+
return False
24+
25+
if __name__ == '__main__':
26+
print(parseParenthesis('((()))')) # True
27+
print(parseParenthesis('((())')) # False
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
# Author: OMKAR PATHAK
2+
3+
import Stack
4+
5+
def isOperand(char):
6+
return (ord(char) >= ord('a') and ord(char) <= ord('z')) or (ord(char) >= ord('A') and ord(char) <= ord('Z'))
7+
8+
def precedence(char):
9+
if char == '+' or char == '-':
10+
return 1
11+
elif char == '*' or char == '/':
12+
return 2
13+
elif char == '^':
14+
return 3
15+
else:
16+
return -1
17+
18+
def infixToPostfix(myExp, myStack):
19+
postFix = []
20+
for i in range(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(not myStack.isEmpty() and topOperator != '('):
28+
postFix.append(topOperator)
29+
topOperator = myStack.pop()
30+
else:
31+
while (not myStack.isEmpty()) and (precedence(myExp[i]) <= precedence(myStack.peek())):
32+
postFix.append(myStack.pop())
33+
myStack.push(myExp[i])
34+
35+
while(not myStack.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 = [i for i in myExp]
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

+50
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
# Author: OMKAR PATHAK
2+
3+
class Stack(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) for i in self.stack])
11+
12+
# for pushing an element on to the stack
13+
def push(self, data):
14+
if len(self.stack) >= self.limit:
15+
print('Stack Overflow')
16+
else:
17+
self.stack.append(data)
18+
19+
# for popping the uppermost element
20+
def pop(self):
21+
if len(self.stack) <= 0:
22+
return -1
23+
else:
24+
return self.stack.pop()
25+
26+
# for peeking the top-most element of the stack
27+
def peek(self):
28+
if len(self.stack) <= 0:
29+
return -1
30+
else:
31+
return self.stack[len(self.stack) - 1]
32+
33+
# to check if stack is empty
34+
def isEmpty(self):
35+
return self.stack == []
36+
37+
# for checking the size of stack
38+
def size(self):
39+
return len(self.stack)
40+
41+
if __name__ == '__main__':
42+
myStack = Stack()
43+
for i in range(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

+56
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+
from P26_InsertionSort import insertionSort
17+
import math
18+
19+
DEFAULT_BUCKET_SIZE = 5
20+
21+
def bucketSort(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+
for i in range(0, len(myList)):
30+
if myList[i] < minValue:
31+
minValue = myList[i]
32+
elif myList[i] > maxValue:
33+
maxValue = myList[i]
34+
35+
# Initialize buckets
36+
bucketCount = math.floor((maxValue - minValue) / bucketSize) + 1
37+
buckets = []
38+
for i in range(0, bucketCount):
39+
buckets.append([])
40+
41+
# For putting values in buckets
42+
for i in range(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+
for i in range(0, len(buckets)):
48+
insertionSort(buckets[i])
49+
for j in range(0, len(buckets[i])):
50+
sortedArray.append(buckets[i][j])
51+
52+
return sortedArray
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)