0% found this document useful (0 votes)
6 views57 pages

DATA STRUCTURE FINAL LAB MANUAL

The document contains various coding examples demonstrating data structures and algorithms, including stack, queue, list operations, Fibonacci sequence generation, polynomial addition, infix to postfix conversion, scheduling algorithms, searching algorithms, sorting algorithms, hash tables, and binary trees. Each section includes code snippets and their respective outputs. The examples illustrate fundamental programming concepts and techniques in Python.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views57 pages

DATA STRUCTURE FINAL LAB MANUAL

The document contains various coding examples demonstrating data structures and algorithms, including stack, queue, list operations, Fibonacci sequence generation, polynomial addition, infix to postfix conversion, scheduling algorithms, searching algorithms, sorting algorithms, hash tables, and binary trees. Each section includes code snippets and their respective outputs. The examples illustrate fundamental programming concepts and techniques in Python.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 57

Coding :

Stack:
stack = []
stack.append('a')
stack.append('b')
stack.append('c')
print('Initial stack')
print(stack)
print('\nElements poped from stack:')
print(stack.pop())
print(stack.pop())
print(stack.pop())
print('\nStack after elements are poped:')
print(stack)

Queue:
queue = []
queue.append('a')
queue.append('b')
queue.append('c')
print("Initial queue")
print(queue)
print("\nElements dequeued from 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("Initial List: ")
print(List)
List.extend([8, 'Geeks', 'Always'])
print("\nList after performing Extend Operation: ")
print(List)
Output:
Stack:
Initial stack
['a', 'b', 'c']
Elements poped from stack:
c
b
a
Stack after elements are poped:
[]
Queue:
['a', 'b', 'c']
Elements dequeued from queue:
A
b
c
Queue after removing elements
[]
List:
Initial List:
[1, 2, 3, 4]
List after performing Extend Operation:
[1, 2, 3, 4, 8, 'Geeks', 'Always']
Coding:

No = 10
num1, num2 = 0, 1
count = 0
if No <= 0:
print("Invalid Number")
elif No == 1:
print("Fibonacci sequence for limit of ",No,":")
print(num1)
else:
print("Fibonacci sequence:")
while count < No:
print(num1)
nth = num1 + num2
num1 = num2
num2 = nth
count += 1
Output:
Fibonacci sequence:
0
1
1
2
3
5
8
13
21
34
Coding:

Class node:
def __init__(self,data):
self.data=data
self.next=none
def add(self,data):
nn=none(data)
nn.next=None
return nn
def printarray(self,a,n):
i=0
while(i<n)
print(a[i],end=””)
i=i+1
def findlength(self,head)
cur=head
count=0
while(cur!=None):
count=count+1
cur=cur.next
return count
def convertarr(self,head):
length=self.findlength(head)
arr=[]
index=0
cur=head
while(cur!=None):
arr.append(cur.data)
cur=cur.next
self.printarray(arr,length)
head=node(0)
head=head.add(6)
head.next=head.add(4)
head.next.next=head.add(3)
head.next.next.next=head.add(4)
head.next.next.next.next=head.add(9)
head.convertarr(head)
Output:
[6,4,3,4]
[6 4 3 4]
Coding:

List = [1,2,3,4]
print("Initial List: ")
print(List)
List.extend([8, 'Geeks', 'Always'])
print("\nList after performing Extend Operation: ")
print(List) List = []
print("Blank List: ")
print(List)
List = [10, 20, 14]
print("\nList of numbers: ")
print(List)
List = ["Geeks", "For", "Geeks"]
print("\nList Items: ")
print(List[0])
print(List[2])
Adding the elements:
List = [1,2,3,4]
print("Initial List: ")
print(List)
List.insert(3, 12)
List.insert(0, 'Geeks')
print("\nList after performing Insert Operation: ")
print(List)
List = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
print("Intial List: ")
print(List)
List.remove(5)
List.remove(6)
print("\nList after Removal of two elements: ")
print(List)
for i in range(1, 5):
List.remove(i)
print("\nList after Removing a range of elements: ")
print(List)
List = [['Geeks', 'For'] , ['Geeks']]
print("\nMulti-Dimensional List: ")
print(List)
Output:
Initial blank List:
[]
List after Addition of Three elements:
[1, 2, 4]
List after Addition of elements from 1-3:
[1, 2, 4, 1, 2, 3]
>>>
===================== RESTART: Z:/New folder/queue 1.py
=====================
Initial List:
[1, 2, 3, 4]
List after performing Insert Operation:
['Geeks', 1, 2, 3, 12, 4]
>>>
===================== RESTART: Z:/New folder/queue 1.py
=====================
Intial List:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
List after Removal of two elements:
[1, 2, 3, 4, 7, 8, 9, 10, 11, 12]
List after Removing a range of elements:
[7, 8, 9, 10, 11, 12]
Coding:
stack = []
stack.append('a')
stack.append('b')
stack.append('c')
print('Initial stack')
print(stack)
print('\nElements poped from stack:')
print(stack.pop())
print(stack.pop())
print(stack.pop())
print('\nStack after elements are poped:')
print(stack)
Queue:

queue = []
queue.append('a')
queue.append('b')
queue.append('c')
print("Initial queue")
print(queue)
print("\nElements dequeued from queue")
print(queue.pop(0))
print(queue.pop(0))
print(queue.pop(0))
print("\nQueue after removing elements")
print(queue)
Output:
Initial stack
['a', 'b', 'c']
Elements poped from stack:
c
b
a
Stack after elements are poped:
[]
Coding:

def add(A, B, m, n):


size = max(m, n);
sum = [0 for i in range(size)]
for i in range(0, m, 1):
sum[i] = A[i]
for i in range(n):
sum[i] += B[i]
return sum
def printPoly(poly, n):
for i in range(n):
print(poly[i], end = "")
if (i != 0):
print("x^", i, end = "")
if (i != n - 1):
print(" + ", end = "")
if __name__ == '__main__':
A = [5, 0, 10, 6]
B = [1, 2, 4]
m = len(A)
n = len(B)
print("First polynomial is")
printPoly(A, m)
print("\n", end = "")
print("Second polynomial is")
printPoly(B, n)
print("\n", end = "")
sum = add(A, B, m, n)
size = max(m, n)
print("sum polynomial is")
printPoly(sum, size)
Output:
First polynomial is
5 + 0x^1 + 10x^2 + 6x^3
Second polynomial is
1 + 2x^1 + 4x^2
Sum polynomial is
6 + 2x^1 + 14x^2 + 6x^3
Coding:

class Conversion:
def __init__(self, capacity):
self.top = -1
self.capacity = capacity
self.array = []
self.output = []
self.precedence = {'+':1, '-':1, '*':2, '/':2, '^':3}
def isEmpty(self):
return True if self.top == -1 else False
def peek(self):
return self.array[-1]
def pop(self):
if not self.isEmpty():
self.top -= 1
return self.array.pop()
else:
return "$"
def push(self, op):
self.top += 1
self.array.append(op)
def isOperand(self, ch):
return ch.isalpha()
def notGreater(self, i):
try:
a = self.precedence[i]
b = self.precedence[self.peek()]
return True if a <= b else False
except KeyError:
return False
def infixToPostfix(self, exp):
for i in exp:
if self.isOperand(i):
self.output.append(i)

elif i == '(':
self.push(i)

elif i == ')':
while( (not self.isEmpty()) and
self.peek() != '('):
a = self.pop()
self.output.append(a)
if (not self.isEmpty() and self.peek() != '('):
return -1
else:
self.pop()
else:
while(not self.isEmpty() and self.notGreater(i)):
self.output.append(self.pop())
self.push(i)
while not self.isEmpty():
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-
Coding:

def findWaitingTime(processes, n, bt, wt):


wt[0] = 0
for i in range(1, n):
wt[i] = bt[i - 1] + wt[i - 1]

def findTurnAroundTime(processes, n, bt, wt, tat):


# calculating turnaround
# time by adding bt[i] + wt[i]
for i in range(n):
tat[i] = bt[i] + wt[i]

def findavgTime(processes, n, bt):


wt = [0] * n
tat = [0] * n
total_wt = 0
total_tat = 0

findWaitingTime(processes, n, bt, wt)


findTurnAroundTime(processes, n, bt, wt, tat)
print("Processes Burst time Waiting time Turn around time")

for i in range(n):
total_wt = total_wt + wt[i]
total_tat = total_tat + tat[i]
print(" " + str(i + 1) + "\t\t" + str(bt[i]) + "\t " str(wt[i])
+ "\t\t " +str(tat[i]))
print( "Average waiting time = "+ str(total_wt / n))
print("Average turn around time = "+ str(total_tat / n))
if __name__ =="__main__":
processes = [ 1, 2, 3]
n = len(processes)
burst_time = [10, 5, 8]
findavgTime(processes, n, burst_time)
Output:

Processes Burst time Waiting time Turn around time


1 10 0 10
2 5 10 15
3 8 15 23
Average waiting time = 8.33333
Average turn around time = 16
Coding:

def BinarySearch(arr, low, high, key):


if high >= low:
mid = (high + low) // 2
if arr[mid] == key:
return mid
elif arr[mid] > key:
return BinarySearch(arr, low, mid - 1, key)
else:
return BinarySearch(arr, mid + 1, high, key)
else:
return -1

arr = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
key = 40
result = BinarySearch(arr, 0, len(arr)-1, key)
if result != -1:
print(key, "Found at index", str(result))
else:
print(key, "not Found")

def linearsearch(arr, x):


for i in range(len(arr)):
if arr[i] == x:
return i
return -1

arr = ['t', 'u', 't', 'o', 'r', 'i', 'a', 'l']


x = 'a'
print("element found at index " + str(linearsearch(arr, x)))
Output of Binary Search:
40 Found at index 3
Output of Linear Search:
element found at index 6
Coding:

def partition(arr,low,high):
i = ( low-1 )
pivot = arr[high]
for j in range(low , high):
if arr[j] <= pivot:
i = i+1
arr[i],arr[j] = arr[j],arr[i]
arr[i+1],arr[high] = arr[high],arr[i+1]
return ( i+1 )
def quickSort(arr,low,high):
if low < high:

pi = partition(arr,low,high)
quickSort(arr, low, pi-1)
quickSort(arr, pi+1, high)

arr = [2,5,3,8,6,5,4,7]
n = len(arr)
quickSort(arr,0,n-1)
print ("Sorted array is:")
for i in range(n):
print (arr[i],end=" ")
def insertionSort(arr):
for i in range(1, len(arr)):
key = arr[i]

j = i-1
while j >=0 and key < arr[j] :
arr[j+1] = arr[j]
j -= 1
arr[j+1] = key

arr = ['t','u','t','o','r','i','a','l']
insertionSort(arr)
print ("The sorted array is:")
for i in range(len(arr)):
print (arr[i])
Output:
Quick Sorted array is:
23455678
Insertion sorted array is:
a
i
l
o
r
t
t
u
Coding:

hashTable = [[],] * 10
def checkPrime(n):
if n == 1 or n == 0:
return 0
for i in range(2, n//2):
if n % i == 0:
return 0
return 1
def getPrime(n):
if n % 2 == 0:
n=n+1
while not checkPrime(n):
n += 2
return n
def hashFunction(key):
capacity = getPrime(10)
return key % capacity
def insertData(key, data):
index = hashFunction(key)
hashTable[index] = [key, data]
def removeData(key):
index = hashFunction(key)
hashTable[index] = 0
insertData(123, "apple")
insertData(432, "mango")
insertData(213, "banana")
insertData(654, "guava")
print(hashTable)
removeData(123)

print(hashTable)
Output:
[[], [], [123, 'apple'], [432, 'mango'], [213, 'banana'], [654, 'guava'], [], [], [], []]
[[], [], 0, [432, 'mango'], [213, 'banana'], [654, 'guava'], [], [], [], []]
Coding:

class Node:
def __init__(self, data):
self.left = None
self.right = None
self.data = data
def insert(self, data):
if self.data:
if data < self.data:
if self.left is None:
self.left = Node(data)
else:
self.left.insert(data)
elif data > self.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()
print( self.data),
if self.right:
self.right.PrintTree()
root = Node(12)
root.insert(6)
root.insert(14)
root.insert(3)

root.PrintTree()
Output:
3
6
12
14
Coding:

class Node:
def __init__(self,key):
self.left = None
self.right = None
self.val = key
def printInorder(root):
if root:
printInorder(root.left)
print(root.val),
printInorder(root.right)
def printPostorder(root):
if root:
printPostorder(root.left)
printPostorder(root.right)
print(root.val),
def printPreorder(root):
if root:
print(root.val),
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)
print ("\nPreorder traversal of binary tree is")
printPreorder(root)
print ("\nInorder traversal of binary tree is")
printInorder(root)
print ("\nPostorder traversal of binary tree is")
printPostorder(root)
Output:
Preorder traversal of binary tree is
1
2
4
5
3
Inorder traversal of binary tree is
4
2
5
1
3
Postorder traversal of binary tree is
4
5
2
3
1
Coding:

class Node:
def __init__(self, data):
self.left = None
self.right = None
self.data = data

def insert(self, data):


if self.data:
if data < self.data:
if self.left is None:
self.left = Node(data)
else:
self.left.insert(data)
elif data > self.data:
if self.right is None:
self.right = Node(data)
else:
self.right.insert(data)
else:
self.data = data
def findval(self, lkpval):
if lkpval < self.data:
if self.left is None:
return str(lkpval)+" Not Found"
return self.left.findval(lkpval)
elif lkpval > self.data:
if self.right is None:
return str(lkpval)+" Not Found"
return self.right.findval(lkpval)
else:
return str(self.data) + ' is found'

def PrintTree(self):
if self.left:
self.left.PrintTree()
print( self.data),
if self.right:
self.right.PrintTree()
root = Node(12)
root.insert(6)
root.insert(14)
root.insert(3)
print(root.findval(7))
Output:
7 Not Found
14 is found
Coding:

import heapq
H = [21,1,45,78,3,5]
heapq.heapify(H)
print(H)
heapq.heappush(H,8)
print(H)
heapq.heappop(H)
print(H)
Output:
1, 3, 5, 78, 21, 45
[1, 3, 5, 78, 21, 45, 8]
[3, 8, 5, 78, 21, 45]
Coding:

class graph:
def __init__(self,gdict=None):
if gdict is None:
gdict = []
self.gdict = gdict
def getVertices(self):
return list(self.gdict.keys())
graph_elements = { "a" : ["b","c"],
"b" : ["a", "d"],
"c" : ["a", "d"],
"d" : ["e"],
"e" : ["d"]
}
g = graph(graph_elements)
print(g.getVertices())
class graph:
def __init__(self,gdict=None):
if gdict is None:
gdict = {}
self.gdict = gdict
def edges(self):
return self.findedges()
def findedges(self):
edgename = []
for vrtx in self.gdict:
for nxtvrtx in self.gdict[vrtx]:
if {nxtvrtx, vrtx} not in edgename:
edgename.append({vrtx, nxtvrtx})
return edgename
graph_elements = { "a" : ["b","c"],
"b" : ["a", "d"],
"c" : ["a", "d"],
"d" : ["e"],

"e" : ["d"]
}
g = graph(graph_elements)
print(g.edges())
Output:
DISPLAYING VERTICES
['a', 'b', 'c', 'd', 'e']
DISPLAYING EDGES
[{'a', 'b'}, {'a', 'c'}, {'d', 'b'}, {'c', 'd'}, {'d', 'e'}]
Coding:

BFS
import collections
def bfs(graph, root):
visited, queue = set(), collections.deque([root])
visited.add(root)
while queue:
vertex = queue.popleft()
print(str(vertex) + " ", end="")
for neighbour in graph[vertex]:
if neighbour not in visited:
visited.add(neighbour)
queue.append(neighbour)
if __name__ == '__main__':
graph = {0: [1, 2], 1: [2], 2: [3], 3: [1, 2]}
print("Following is Breadth First Traversal: ")
bfs(graph, 0)

DFS
import sys
def ret_graph():
return {
'A': {'B':5.5, 'C':2, 'D':6},
'B': {'A':5.5, 'E':3},
'C': {'A':2, 'F':2.5},
'D': {'A':6, 'F':1.5},
'E': {'B':3, 'J':7},
'F': {'C':2.5, 'D':1.5, 'K':1.5, 'G':3.5},
'G': {'F':3.5, 'I':4},
'H': {'J':2},
'I': {'G':4, 'J':4},
'J': {'H':2, 'I':4},
'K': {'F':1.5}
}
start = 'A'
dest = 'J'
visited = []

stack = []
graph = ret_graph()
path = []
stack.append(start)
visited.append(start)
while stack:
curr = stack.pop()
path.append(curr)
for neigh in graph[curr]:
if neigh not in visited:
visited.append(neigh)
stack.append(neigh)
if neigh == dest :
print("FOUND:", neigh)
print(path)
sys.exit(0)
print("Not found")
print(path)
Output:
BFS Following is Breadth First Traversal: 0 1 2 3
Output:
DFS FOUND: J ['A', 'D', 'F', 'G', 'I']
Coding:

from sys import maxsize


def BellmanFord(graph, V, E, src):
dis = [maxsize] * V
dis[src] = 0
for i in range(V - 1):
for j in range(E):
if dis[graph[j][0]] +graph[j][2] < dis[graph[j][1]]:
dis[graph[j][1]] = dis[graph[j][0]] + graph[j][2]
for i in range(E):
x = graph[i][0]
y = graph[i][1]
weight = graph[i][2]
if dis[x] != maxsize and dis[x] + weight < dis[y]:
print("Graph contains negative weight cycle")
print("Vertex Distance from Source")
for i in range(V):
print("%d\t\t%d" % (i, dis[i]))

if __name__ == "__main__":
V = 5 # Number of vertices in graph
E = 8 # Number of edges in graph
graph = [[0, 1, -1], [0, 2, 4], [1, 2, 3],
[1, 3, 2], [1, 4, 2], [3, 2, 5],
[3, 1, 1], [4, 3, -3]]
BellmanFord(graph, V, E, 0)
Output:
Vertex Distance from Source
0 0
1 -1
2 2
3 -2
Coding:

class Graph:
def __init__(self, vertices):
self.V = vertices
self.graph = []

def add_edge(self, u, v, w):


self.graph.append([u, v, w])

def find(self, parent, i):


if parent[i] == i:
return i
return self.find(parent, parent[i])

def apply_union(self, parent, rank, x, y):


xroot = self.find(parent, x)
yroot = self.find(parent, y)
if rank[xroot] < rank[yroot]:
parent[xroot] = yroot
elif rank[xroot] > rank[yroot]:
parent[yroot] = xroot
else:
parent[yroot] = xroot
rank[xroot] += 1
def kruskal_algo(self):
result = []
i, e = 0, 0
self.graph = sorted(self.graph, key=lambda item: item[2])
parent = [i for i in range(self.V)]
rank = [0] * self.V

while e < self.V - 1:


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)

for u, v, weight in result:


print("%d - %d: %d" % (u, v, weight))

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

You might also like