DSA Program Print-Out
DSA Program Print-Out
PROGRAM:
STACK:
stack = []
stack.append('a')
stack.append('b')
stack.append('c')
print('Initial stack')
print(stack)
print(stack.pop())
print(stack.pop())
print(stack.pop())
print(stack)
QUEUE:
queue = []
queue.append('a')
queue.append('b')
queue.append('c')
print("Initial queue")
print(queue)
print(queue.pop(0))
print(queue.pop(0))
print(queue.pop(0))
print("\nQueue after removing elements")
print(queue)
LIST:
List = [1,2,3,4]
print(List)
print(List)
OUTPUT:
STACK:
Initial stack
[]
QUEUE:
Initial queue
[]
LIST:
Initial List:
[1, 2, 3, 4]
PROGRAM:
No = 10
num1, num2 = 0, 1
count = 0
if No <= 0:
print("Invalid Number")
elif No == 1:
print(num1)
else:
print("Fibonacci sequence:")
print(num1)
num1 = num2
num2 = nth
count += 1
OUTPUT:
Fibonacci sequence:
13
21
34
3. LIST ADT USING PYTHON ARRAYS
PROGRAM:
class node:
self.data = data
self.next = None
def add(data):
nn = node(0)
nn.data = data
nn.next = None
return nn
i=0
while i < n:
i =i+1
print()
def findlength(head):
cur = head
count = 0
while(cur!=None):
count=count+1
cur = cur.next
return count
def convertarr(head):
len = node.findlength(head)
arr = []
index=0
cur = head
while(cur!=None):
arr.append(cur.data)
cur = cur.next
node.printarray(arr, len)
head= node(0)
head = node.add(6)
head.next = node.add(4)
head.next.next = node.add(3)
head.next.next.next = node.add(4)
node.convertarr(head)
OUTPUT:
[6 4 3 4]
4. LINKED LIST IMPLEMENTATIONS OF LIST
PROGRAM:
my_list = []
print(my_list)
my_list.append(1)
my_list.append(2)
my_list.append(4)
print(my_list)
my_list.extend([1, 2, 3])
print(my_list)
my_list = [1, 2, 3, 4]
print("Initial List:")
print(my_list)
my_list.insert(0, 'Geeks')
my_list.insert(4, 12)
print(my_list)
print("Initial List:")
print(my_list)
my_list.remove(5)
my_list.remove(6)
print(my_list)
my_list = my_list[4:]
print(my_list)
OUTPUT:
[]
[1, 2, 4]
[1, 2, 4, 1, 2, 3]
Initial List:
[1, 2, 3, 4]
['Geeks', 1, 2, 3, 12, 4]
Initial List:
PROGRAM:
STACK:
stack = []
stack.append('a')
stack.append('b')
stack.append('c')
print('Initial stack')
print(stack)
print(stack.pop())
print(stack.pop())
print(stack.pop())
print(stack)
QUEUE:
queue = []
queue.append('a')
queue.append('b')
queue.append('c')
print("Initial queue")
print(queue)
print(queue.pop(0))
print(queue.pop(0))
print(queue.pop(0))
print(queue)
OUTPUT:
STACK:
Initial stack
[]
QUEUE:
Initial queue
[]
6. A) APPLICATION OF LIST
PROGRAM:
size = max(m, n)
for i in range(m):
sum[i] = A[i]
for i in range(n):
sum[i] += B[i]
return sum
for i in range(n):
print(poly[i], end="")
if i != 0:
print("x^", i, end="")
if i != n - 1:
print()
if __name__ == "__main__":
A = [5, 0, 10, 6]
B = [1, 2, 4]
m = len(A)
n = len(B)
printPoly(B, n)
sum = add(A, B, m, n)
size = max(m, n)
printPoly(sum, size)
OUTPUT:
First polynomial is
Second polynomial is
1 + 2x^ 1 + 4x^ 2
Sum polynomial is
PROGRAM:
class Conversion:
self.top = -1
self.capacity = capacity
self.array = []
self.output = []
def isEmpty(self):
def peek(self):
return self.array[-1]
def pop(self):
if not self.isEmpty():
self.top -= 1
return self.array.pop()
else:
return "$"
self.top += 1
self.array.append(op)
return ch.isalpha()
try:
a = self.precedence[i]
b = self.precedence[self.peek()]
except KeyError:
return False
for i in exp:
if self.isOperand(i):
self.output.append(i)
elif i == '(':
self.push(i)
elif i == ')':
a = self.pop()
self.output.append(a)
return -1
else:
self.pop()
else:
self.output.append(self.pop())
self.push(i)
self.output.append(self.pop())
print("".join(self.output))
exp = "a+b*(c^d-e)^(f+g*h)-i"
obj = Conversion(len(exp))
obj.infixToPostfix(exp)
OUTPUT:
abcd^e-fgh*+^*+i-
6. C) APPLICATION OF QUEUE
PROGRAM:
wt[0] = 0
for i in range(n):
wt = [0] * n
tat = [0] * n
total_wt = 0
total_tat = 0
for i in range(n):
if __name__ == "__main__":
processes = [1, 2, 3]
n = len(processes)
burst_time = [10, 5, 8]
findavgTime(processes, n, burst_time)
OUTPUT:
1 10 0 10
2 5 10 15
3 8 15 23
PROGRAM:
list_of_elements = [4, 3, 8, 9, 2, 7]
found = False
for i in range(len(list_of_elements)):
if list_of_elements[i] == x:
found = True
break
if not found:
PROGRAM:
item_list.sort()
first = 0
last = len(item_list) - 1
found = False
if item_list[mid] == item:
found = True
else:
last = mid - 1
else:
first = mid + 1
return found
False
True
7. C) SELECTION SORT
PROGRAM:
def selectionSort(alist):
positionOfMax = 0
positionOfMax = location
temp = alist[fillslot]
alist[fillslot] = alist[positionOfMax]
alist[positionOfMax] = temp
alist = [45, 62, 13, 71, 77, 31, 49, 53, 20]
selectionSort(alist)
print(alist)
OUTPUT:
PROGRAM:
def insertionSort(alist):
currentvalue = alist[index]
position = index
alist[position] = alist[position - 1]
position = position - 1
alist[position] = currentvalue
alist = [15, 22, 39, 41, 67, 73, 85, 86, 90]
insertionSort(alist)
print(alist)
OUTPUT:
PROGRAM:
def checkPrime(n):
if n <= 1:
return False
if n % i == 0:
return False
return True
def getPrime(n):
if n % 2 == 0:
n += 1
n += 2
return n
def hashFunction(key):
capacity = getPrime(10)
index = hashFunction(key)
if pair[0] == key:
pair[1] = data
return
hashTable[index].append([key, data])
def removeData(key):
index = hashFunction(key)
if pair[0] == key:
del hashTable[index][i]
return
insertData(123, "apple")
insertData(432, "mango")
insertData(213, "banana")
insertData(654, "guava")
removeData(123)
Hash table after insertion: [[], [], [[123, 'apple']], [[432, 'mango']], [[213, 'banana']], [[654, 'guava']], [], [], [], []]
Hash table after deletion: [[], [], [], [[432, 'mango']], [[213, 'banana']], [[654, 'guava']], [], [], [], []]
9. A) TREE REPRESENTATION
PROGRAM:
class Node:
self.left = None
self.right = None
self.data = data
if self.data:
if self.left is None:
self.left = Node(data)
else:
self.left.insert(data)
if self.right is None:
self.right = Node(data)
else:
self.right.insert(data)
else:
self.data = data
def PrintTree(self):
if self.left:
self.left.PrintTree()
self.right.PrintTree()
root = Node(12)
root.insert(6)
root.insert(14)
root.insert(3)
root.PrintTree()
OUTPUT:
12
14
9. B) TREE TRAVERSAL ALGORITHMS
PROGRAM:
class Node:
self.left = None
self.right = None
self.val = key
def printInorder(root):
if root:
printInorder(root.left)
printInorder(root.right)
def printPostorder(root):
if root:
printPostorder(root.left)
printPostorder(root.right)
def printPreorder(root):
if root:
printPreorder(root.left)
printPreorder(root.right)
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
printPreorder(root)
printInorder(root)
printPostorder(root)
OUTPUT:
12453
42513
45231
10. IMPLEMENTATION OF BINARY SEARCH TREES
PROGRAM:
class Node:
self.left = None
self.right = None
self.data = data
if self.data:
if self.left is None:
self.left = Node(data)
else:
self.left.insert(data)
if self.right is None:
self.right = Node(data)
else:
self.right.insert(data)
else:
self.data = data
if self.left is None:
if self.right is None:
return self.right.findval(lkpval)
else:
def PrintTree(self):
if self.left:
self.left.PrintTree()
if self.right:
self.right.PrintTree()
root = Node(12)
root.insert(6)
root.insert(14)
root.insert(3)
print(root.findval(7))
print("Tree traversal:")
root.PrintTree()
OUTPUT:
7 Not Found
Tree traversal:
3 6 12 14
11. IMPLEMENTATION OF HEAPS
PROGRAM:
import heapq
heapq.heapify(H)
print("Heapified list:", H)
heapq.heappush(H, 8)
heapq.heappop(H)
PROGRAM:
class Graph:
if gdict is None:
gdict = {}
self.gdict = gdict
def getVertices(self):
return list(self.gdict.keys())
def edges(self):
return self.find_edges()
def find_edges(self):
edge_list = []
edge_list.append({vertex, next_vertex})
return edge_list
graph_elements = {
"d": ["e"],
"e": ["d"]
}
g = Graph(graph_elements)
Edges of graph: [{'b', 'a'}, {'c', 'a'}, {'b', 'd'}, {'c', 'd'}, {'e', 'd'}]
12. B) GRAPH TRAVERSAL ALGIRITHMS
PROGRAM:
BFS:
import collections
visited.add(root)
while queue:
vertex = queue.popleft()
visited.add(neighbour)
queue.append(neighbour)
if __name__ == '__main__':
bfs(graph, 0)
DFS:
import sys
def ret_graph():
return {
start = 'A'
dest = 'J'
visited = []
stack = []
graph = ret_graph()
path = []
stack.append(start)
visited.append(start)
while stack:
curr = stack.pop()
path.append(curr)
if curr == dest:
print("FOUND:", curr)
print(path)
break
visited.append(neigh)
stack.append(neigh)
print("Not found")
print(path)
OUTPUT:
BFS:
0123
DFS:
FOUND: J
PROGRAM:
dis = [maxsize] * V
dis[src] = 0
for j in range(E):
u, v, w = graph[j]
dis[v] = dis[u] + w
for i in range(E):
u, v, w = graph[i]
return
for i in range(V):
print(f"{i}\t\t{dis[i]}")
if __name__ == "__main__":
V=5
E=8
graph = [
BellmanFord(graph, V, E, 0)
OUTPUT:
0 0
1 -1
2 2
3 -2
4 1
14. IMPLEMENTATION OF MINIMUM SPANNING
TREE ALGORITHMS
PROGRAM:
class Graph:
self.V = vertices
self.graph = []
self.graph.append([u, v, w])
if parent[i] == i:
return i
xroot = self.find(parent, x)
yroot = self.find(parent, y)
parent[xroot] = yroot
parent[yroot] = xroot
else:
parent[yroot] = xroot
rank[xroot] += 1
def kruskal_algo(self):
result = []
i, e = 0, 0
parent = []
rank = []
parent.append(node)
rank.append(0)
u, v, w = self.graph[i]
i += 1
x = self.find(parent, u)
y = self.find(parent, v)
if x != y:
e += 1
result.append([u, v, w])
self.apply_union(parent, rank, x, y)
g = Graph(6)
g.add_edge(0, 1, 4)
g.add_edge(0, 2, 4)
g.add_edge(1, 2, 2)
g.add_edge(1, 0, 4)
g.add_edge(2, 0, 4)
g.add_edge(2, 1, 2)
g.add_edge(2, 3, 3)
g.add_edge(2, 5, 2)
g.add_edge(2, 4, 4)
g.add_edge(3, 2, 3)
g.add_edge(3, 4, 3)
g.add_edge(4, 2, 4)
g.add_edge(4, 3, 3)
g.add_edge(5, 2, 2)
g.add_edge(5, 4, 3)
g.kruskal_algo()
OUTPUT:
1 - 2: 2
2 - 5: 2
2 - 3: 3
3 - 4: 3
0 - 1: 4