DSD Lab Manual
DSD Lab Manual
REGULATION - 2021
I Year/ II Semester
Lab Manual
Prepared by
K.Sathish Kumar, AP/CSE
HOD PRINCIPAL
SYLLABUS
OBJECTIVES:
• To implement ADTs in Python.
• To design and implement linear data structures – lists, stack and queues.
• To implement sorting, searching and hashing algorithms.
• To solve problem using tree structures.
• To solve problem using graph structures.
LIST OF EXPERIMENTS:
OUTCOMES:
Upon completion of the course, the students will be able to
INDEX
Algorithm:
Program:
class perimeter():
height=float(input("Enter the height ="))
width=float(input("Enter the width ="))
perim= (height*2)+(width*2)
print("Perimeter = ",perim)
class area(perimeter):
def fun(self):
area1=ar.height*ar.width
print("Area = ",area1)
ar=area()
ar.fun()
Output :
Result:
Thus, the above program for ADTs python classes was successfully completed.
Algorithm :
Step 1: Start
Step 2: Read number n
Step 3: Call factorial(n)
Step 4: Print factorial f
Step 5: Stop
factorial(n)
Step 1: If n==1 then return 1
Step 2: Else
f=n*factorial(n-1)
Step 3: Return
Program:
def factorial(num):
if (num == 0):
return 1
else:
return num * factorial(num - 1)
print('{}! is {}'.format(4, factorial(4)))
print('{}! is {}'.format(2, factorial(2)))
Output:
4! is 24
2! is 2
Result:
Thus, the above program for implementing factorial using recursion was successfully
completed.
Aim: Write a Python program to implement Fibonacci Series using recursive algorithm.
Algorithm :
Program:
def fibonacci(n):
if(n <= 1):
return n
else:
return(fibonacci(n-1) + fibonacci(n-2))
n = int(input("Enter number of terms:"))
print("Fibonacci sequence:")
for i in range(n):
print(fibonacci(i))
Output:
0
1
1
2
3
5
Result:
Thus, the above program for implementing Fibonacci series using recursion
was successfully completed.
Aim: Write a Python program to implement List ADT using Python arrays.
Algorithm :
Program:
import array
arr = array.array('i', [1, 2, 3])
print ("The new created array is : ",end=" ")
for i in range (0, 3):
print (arr[i], end=" ")
print("\r")
arr.append(4)
print("The appended array is : ", end="")
for i in range (0, 4):
print (arr[i], end=" ")
arr.insert(2, 5)
print("\r")
print ("The array after insertion is : ", end="")
for i in range (0, 5):
print (arr[i], end=" ")
print("\r")
print ("The popped element is : ",end="")
print (arr.pop(2));
# printing array after popping
print ("The array after popping is : ",end="")
for i in range (0,4):
print (arr[i],end=" ")
print("\r")
# using remove() to remove 1st occurrence of 1
arr.remove(1)
# printing array after removing
print ("The array after removing is : ",end="")
Output :
Result:
Thus, the above program for implementing List ADT using Python arrays was
successfully completed.
Algorithm :
Program:
class Node:
def __init__(self, data):
self.data = data
self.next = next
# Function to insert Node
def insert(root, item):
temp = Node(0)
temp.data = item
temp.next = root
root = temp
return root
def display(root):
while (root != None):
print(root.data, end=" ")
root = root.next
def arrayToList(arr, n):
root = None
for i in range(n - 1, -1, -1):
root = insert(root, arr[i])
return root
# Driver code
if __name__ == '__main__':
arr = [1, 2, 3, 4, 5];
n = len(arr)
root = arrayToList(arr, n);
display(root)
Output :
12345
Result:
Thus, the above program for program for Linked list implementation of List was
successfully completed.
Algorithm:
Program:
class Stack:
def __init__(self):
self.items = []
def is_empty(self):
return self.items == []
def push(self, data):
self.items.append(data)
def pop(self):
return self.items.pop()
s = Stack()
while True:
print('push <value>')
print('pop')
print('quit')
do = input('What would you like to do? ').split()
operation = do[0].strip().lower()
if operation == 'push':
s.push(int(do[1]))
elif operation == 'pop':
if s.is_empty():
print('Stack is empty.')
else:
print('Popped value: ', s.pop())
elif operation == 'quit':
break
Output :
push <value>
pop
quit
What would you like to do? push 5
push <value>
pop
quit
What would you like to do? push 3
push <value>
pop
quit
What would you like to do? pop
Popped value: 3
push <value>
pop
quit
What would you like to do? pop
Popped value: 5
push <value>
pop
quit
What would you like to do? pop
Stack is empty.
push <value>
pop
quit
What would you like to do? quit
Result:
Thus, the above program for Stack ADT was successfully completed.
Algorithm:
Program:
class Queue:
def __init__(self):
self.items = []
def is_empty(self):
return self.items == []
def enqueue(self, data):
self.items.append(data)
def dequeue(self):
return self.items.pop(0)
q = Queue()
while True:
print('enqueue <value>')
print('dequeue')
print('quit')
do = input('What would you like to do? ').split()
operation = do[0].strip().lower()
if operation == 'enqueue':
q.enqueue(int(do[1]))
elif operation == 'dequeue':
if q.is_empty():
print('Queue is empty.')
else:
print('Dequeued value: ', q.dequeue())
elif operation == 'quit':
break
Output :
enqueue <value>
dequeue
quit
What would you like to do? enqueue5
enqueue <value>
dequeue
quit
What would you like to do? enqueue 4
enqueue <value>
dequeue
quit
What would you like to do? enqueue 3
enqueue <value>
dequeue
quit
What would you like to do? enqueue 6
enqueue <value>
dequeue
quit
What would you like to do? dequeue
Dequeued value: 4
enqueue <value>
dequeue
quit
What would you like to do? quit
Result:
Thus, the above program for Queue ADT was successfully completed.
Algorithm:
Program:
open_list = ["[","{","("]
close_list = ["]","}",")"]
# Function to check parentheses
def check(myStr):
stack = []
for i in myStr:
if i in open_list:
stack.append(i)
elif i in close_list:
pos = close_list.index(i)
if ((len(stack) > 0) and
(open_list[pos] == stack[len(stack)-1])):
stack.pop()
else:
return "Unbalanced"
if len(stack) == 0:
return "Balanced"
else:
return "Unbalanced"
# Driver code
string = "{[]{()}}"
print(string,"-", check(string))
string = "[{}{})(]"
print(string,"-", check(string))
string = "((()"
Output :
{[]{()}} - Balanced
[{}{})(] – Unbalanced
((() - Unbalanced
Result:
Thus, the above program for implementing Balancing Symbols using Stack was
successfully completed.
Algorithm:
Program:
def findWaitingTime(processes, n, bt, wt, at):
service_time = [0] * n
service_time[0] = 0
wt[0] = 0
# calculating waiting time
for i in range(1, n):
# Add burst time of previous processes
service_time[i] = (service_time[i - 1] + bt[i - 1])
# Find waiting time for current
# process = sum - at[i]
wt[i] = service_time[i] - at[i]
# If waiting time for a process is in
# negative that means it is already
# in the ready queue before CPU becomes
# idle so its waiting time is 0
if (wt[i] < 0):
wt[i] = 0
# Function to calculate turn around time
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]
Output :
1 5 0 0 5 5
2 9 3 2 11 14
3 6 6 8 14 20
Result:
Thus, the above program for implementing scheduling using Queue was successfully
completed.
Algorithm:
Program:
def bubbleSort(arr):
n = len(arr)
# Traverse through all array elements
for i in range(n):
# Last i elements are already in place
for j in range(0, n-i-1):
# traverse the array from 0 to n-i-1
# Swap if the element found is greater
# than the next element
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
# Driver code to test above
if __name__ == "__main__":
arr = [5, 1, 4, 2, 8]
bubbleSort(arr)
print("Sorted array is:")
for i in range(len(arr)):
print("%d" % arr[i], end=" ")
Output :
Result:
Thus, the above program for implementing Bubble Sort was successfully completed.
Algorithm:
Program:
def insertionSort(arr):
# Traverse through 1 to len(arr)
for i in range(1, len(arr)):
key = arr[i]
# Move elements of arr[0..i-1], that are
# greater than key, to one position ahead
# of their current position
j = i-1
while j >= 0 and key < arr[j] :
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
# Driver code to test above
arr = [12, 11, 13, 5, 6]
insertionSort(arr)
for i in range(len(arr)):
print ("% d" % arr[i])
Output :
5
6
11
12
13
Result:
Thus, the above program for implementing Insertion Sort was successfully completed.
Algorithm:
Program:
import sys
A = [64, 25, 12, 22, 11]
# Traverse through all array elements
for i in range(len(A)):
# Find the minimum element in remaining
# unsorted array
min_idx = i
for j in range(i+1, len(A)):
if A[min_idx] > A[j]:
min_idx = j
# Swap the found minimum element with
# the first element
A[i], A[min_idx] = A[min_idx], A[i]
# Driver code to test above
print ("Sorted array")
for i in range(len(A)):
print("%d" %A[i],end=" ")
Output :
Sorted array
11 12 22 25 64
Result:
Thus, the above program for implementing Selection Sort was successfully completed.
Algorithm:
Program:
def mergeSort(arr):
if len(arr) > 1:
# Finding the mid of the array
mid = len(arr)//2
# Dividing the array elements
L = arr[:mid]
# into 2 halves
R = arr[mid:]
# Sorting the first half
mergeSort(L)
# Sorting the second half
mergeSort(R)
i=j=k=0
# Copy data to temp arrays L[] and R[]
while i < len(L) and j < len(R):
if L[i] <= R[j]:
arr[k] = L[i]
i += 1
else:
arr[k] = R[j]
j += 1
k += 1
# Checking if any element was left
while i < len(L):
arr[k] = L[i]
i += 1
k += 1
while j < len(R):
arr[k] = R[j]
j += 1
k += 1
# Code to print the list
def printList(arr):
for i in range(len(arr)):
print(arr[i], end=" ")
print()
# Driver Code
if __name__ == '__main__':
arr = [12, 11, 13, 5, 6, 7]
print("Given array is", end="\n")
printList(arr)
mergeSort(arr)
print("Sorted array is: ", end="\n")
printList(arr)
Output :
Given array is
12 11 13 5 6 7
Sorted array is:
5 7 7 11 12 13
Result:
Thus, the above program for implementing Merge Sort was successfully completed.
Algorithm:
Program:
Output :
Unsorted Array
[1, 7, 4, 1, 10, 9, -2]
Sorted Array in Ascending Order:
[-2, 1, 1, 4, 7, 9, 10]
Result:
Thus, the above program for implementing Quick Sort was successfully completed.
Algorithm:
Program:
Output :
Result:
Thus, the above program for implementing Linear Search was successfully completed.
Algorithm:
Program:
if result != -1:
print("Element is present at index", str(result))
else:
print("Element is not present in array")
Output :
Result:
Thus, the above program for implementing Binary Search was successfully completed.
Algorithm:
Program :
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'], [], [], [], []]
Result:
Thus, the python program to implement hash table is executed successfully and output
isverified.
Aim: To write a python program to implement tree representation and traversal algorithm.
Pre-order traversal.
Algorithm:
1. Visit the root (we will print it when we visit to show the order of visiting)
2. Traverse the left subtree in pre-order
3. Traverse the right subtree in pre-order
In-order traversal
Visit the root node in between the left and right node (in)
Algorithm:
1. Traverse the left subtree in in-order
2. Visit the root (we will print it when we visit to show the order of visiting)
3. Traverse the right subtree in in-order
Post-order traversal
Visit the root node after (post) visiting the left and right subtree.
Algorithm:
1. Traverse the left subtree in in-order
2. Traverse the right subtree in in-order
3. Visit the root (we will print it when we visit to show the order of visiting)
Program :
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 ("Preorder 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:
Result:
Thus, the above program for tree representation and traversal algorithm was successfully
completed.
Algorithm:
Program:
arr = [ 2, 3, 4, 10, 40 ]
x = 10
# Function call
result = binary_search(arr, 0, len(arr)-1, x)
if result != -1:
print("Element is present at index", str(result))
else:
print("Element is not present in array")
Output:
Result:
Thus, the above program for binary search tree was successfully completed.
Algorithm:
Program:
class MaxHeap:
def __init__(self, maxsize):
self.maxsize = maxsize
self.size = 0
self.Heap = [0] * (self.maxsize + 1)
self.Heap[0] = sys.maxsize
self.FRONT = 1
# Function to return the position of
# parent for the node currently
# at pos
def parent(self, pos):
return pos // 2
# Function to return the position of
# the left child for the node currently
# at pos
def leftChild(self, pos):
return 2 * pos
# Function to return the position of
# the right child for the node currently
# at pos
def rightChild(self, pos):
return (2 * pos) + 1
# Function that returns true if the passed
# node is a leaf node
def isLeaf(self, pos):
if pos >= (self.size//2) and pos <= self.size:
return True
return False
# Function to swap two nodes of the heap
def swap(self, fpos, spos):
self.Heap[fpos], self.Heap[spos] = (self.Heap[spos],
self.Heap[fpos])
# Function to heapify the node at pos
def maxHeapify(self, pos):
# If the node is a non-leaf node and smaller
# than any of its child
if not self.isLeaf(pos):
if (self.Heap[pos] < self.Heap[self.leftChild(pos)] or
self.Heap[pos] < self.Heap[self.rightChild(pos)]):
# Swap with the left child and heapify
# the left child
if (self.Heap[self.leftChild(pos)] >
self.Heap[self.rightChild(pos)]):
self.swap(pos, self.leftChild(pos))
self.maxHeapify(self.leftChild(pos))
# Swap with the right child and heapify
# the right child
else:
self.swap(pos, self.rightChild(pos))
self.maxHeapify(self.rightChild(pos))
# Function to insert a node into the heap
def insert(self, element):
if self.size >= self.maxsize:
return
self.size += 1
self.Heap[self.size] = element
current = self.size
while (self.Heap[current] >
self.Heap[self.parent(current)]):
self.swap(current, self.parent(current))
current = self.parent(current)
# Function to print the contents of the heap
def Print(self):
for i in range(1, (self.size // 2) + 1):
print("PARENT : " + str(self.Heap[i]) +
"LEFT CHILD : " + str(self.Heap[2 * i]) +
"RIGHT CHILD : " + str(self.Heap[2 * i + 1]))
# Function to remove and return the maximum
# element from the heap
def extractMax(self):
popped = self.Heap[self.FRONT]
self.Heap[self.FRONT] = self.Heap[self.size]
self.size -= 1
self.maxHeapify(self.FRONT)
return popped
# Driver Code
if __name__ == "__main__":
print('The maxHeap is ')
maxHeap = MaxHeap(15)
maxHeap.insert(5)
maxHeap.insert(3)
maxHeap.insert(17)
maxHeap.insert(10)
maxHeap.insert(84)
maxHeap.insert(19)
maxHeap.insert(6)
maxHeap.insert(22)
maxHeap.insert(9)
maxHeap.Print()
print("The Max val is " + str(maxHeap.extractMax()))
Output:
The maxHeap is
PARENT : 84LEFT CHILD : 22RIGHT CHILD : 19PARENT : 22LEFT CHILD :
17RIGHT CHILD : 10PARENT : 19LEFT CHILD : 5RIGHT CHILD : 6 PARENT :
17LEFT CHILD : 3RIGHT CHILD : 9
The Max val is 84
Result:
Thus, the above program for heap was successfully completed.
Algorithm:
Program:
graph = { 'A' : ['B','C'], 'B' : ['D', 'E'], 'C' : ['F'], 'D' : [], 'E' : ['F'], 'F' : [] }
visited = [] # List to keep track of visited nodes.
queue = [] #Initialize a queue
def bfs(visited, graph, node):
visited.append(node)
queue.append(node)
while queue:
s = queue.pop(0)
print (s, end = " ")
for neighbour in graph[s]:
if neighbour not in visited:
visited.append(neighbour)
queue.append(neighbour)
# Driver Code
bfs(visited, graph, 'A')
Output:
ABCDEF
Result:
Thus, the above program for Breadth-first search was successfully completed.
Algorithm:
Step 1: Start the program.
Step 2: Pick any node. If it is unvisited, mark it as visited and recur on all its adjacent
nodes.
Step 3: Repeat until all the nodes are visited, or the node to be searched is found.
Step 4: Stop the program.
Program:
graph = {
'A' : ['B','C'],
'B' : ['D', 'E'],
'C' : ['F'],
'D' : [],
'E' : ['F'],
'F' : [] }
visited = set() # Set to keep track of visited nodes.
def dfs(visited, graph, node):
if node not in visited:
print (node)
visited.add(node)
for neighbour in graph[node]:
dfs(visited, graph, neighbour)
# Driver Code
dfs(visited, graph, 'A')
Output:
Result:
Thus, the above program for Depth-first search was successfully completed.
Aim: To write a python program to implement of single source shortest path algorithm.
Algorithm:
Step 1: Start the program.
Step 2: Create a set sptSet (shortest path tree set) that keeps track of vertices included in
shortest path tree, i.e., whose minimum distance from source is calculated and
finalized. Initially, this set is empty.
Step 3: Assign a distance value to all vertices in the input graph. Initialize all distance
values as INFINITE. Assign distance value as 0 for the source vertex so that it is
picked first.
Step 4: While sptSet doesn’t include all vertices:
• Pick a vertex u which is not there in sptSet and has minimum distance value.
• Include u to sptSet.
• Update distance value of all adjacent vertices of u. To update the distance values,
iterate through all adjacent vertices. For every adjacent vertex v, if the sum of a
distance value of u (from source) and weight of edge u-v, is less than the distance
value of v, then update the distance value of v.
Step 5: Stop the program
Program:
Output:
Result:
Thus, the above program for implementation of single source shortest path algorithm
was successfully completed.
Algorithm:
Step 1: Start the program
Step 2: Select a random node.
Step 3: Choose the path with the minimum weight connected to the chosen node.
Step 4: The path will lead you to a new node, position yourself there.
Step 5: Once you have formed/updated the initial tree, choose the path with the minimum
weightthat is connected to the whole tree. Keep in mind that you must avoid creating
cycles.
Step 6: Repeat steps 3 and 4 until you have covered all the vertices.
Step 7: Stop the program
Program:
INF = 9999999
# number of vertices in graph
N=5
#creating graph by adjacency matrix method
G = [[0, 19, 5, 0, 0],
[19, 0, 5, 9, 2],
[5, 5, 0, 1, 6],
[0, 9, 1, 0, 1],
[0, 2, 6, 1, 0]]
selected_node = [0, 0, 0, 0, 0]
no_edge = 0
selected_node[0] = True
# printing for edge and weight
print("Edge : Weight\n")
while (no_edge < N - 1):
minimum = INF
a=0
b=0
for m in range(N):
if selected_node[m]:
for n in range(N):
if ((not selected_node[n]) and G[m][n]):
# not in selected and there is an edge
Output:
Edge : Weight
0-2:5
2-3:1
3-4:1
4-1:2
Result:
Thus, the above program for implementation of minimum spanning tree algorithms was
successfully completed.