cd3291 Data Structure and Algorithm
cd3291 Data Structure and Algorithm
LABORATORY
2021 REGULATION
Name
Reg.No :
Branch :
Year :
Semester : _
LABORATORY RECORD
Mr. /Ms. of
INDEX
EX NO:
1.ADTS AS PYTHON CLASSES
DATE:
Aim:
To write a program to implement sum of all items, smallest number, reverse a string, basic queue
operation in ADTS as python classes
Algorithm:
1d) queue
Program:
1a)
def sum_list(items):
sum_numbers = 0
for x in items:
sum_numbers += x
return sum_number
print(“sum is”,sum_list([1,2,-8]))
1b)
min = list[ 0 ]
for a in list:
if a < min:
min = a
return min
1c)
def createStack():
stack=[]
return stack
def size(stack):
return len(stack)
def isEmpty(stack):
if size(stack) == 0:
return true
def push(stack,item):
stack.append(item)
def pop(stack):
if isEmpty(stack): return
return stack.pop()
def reverse(string):
n = len(string)
stack = createStack()
for i in range(0,n,1):
push(stack,string[i])
string=""
for i in range(0,n,1):
string+=pop(stack)
return string
string="data structures"
string = reverse(string)
1d) queue
class Queue:
self.items = []
def isEmpty(self):
return self.items == []
self.items.insert(0,item)
def dequeue(self):
return self.items.pop()
def size(self):
return len(self.items)
q=Queue()
q.enqueue(4)
q.enqueue('dog')
q.enqueue(True)
print(q.size())
print(q.isEmpty())
print(q.dequeue())
print(q.size())
Output:
sum is -7
Output:
smallest number -8
Output:
Reversed string is serutcurts atad
Output:
3
False
4
2
Result
Thus the program is successfully executed
EX NO:-
2.RECURSIVE ALGORITHM
DATE:-
Aim:
Write a program to perform tower of hanoi , factorial of a number, fibbonaci series, pascal triangle
using recursive algorithm
2a.Tower of Hanoi:
Algorithm:
1. Create a tower_of_hanoi recursive function and pass two arguments: the number of disks n
and the name of the rods such as source, auxiliary, and target.
2. define the base case when the number of disks is 1. In this case, simply move the one disk from
the source to target and return.
3. Now, move remaining n-1 disks from source to auxiliary using the target as the auxiliary.
4. Then, the remaining 1 disk move on the source to target.
5. Move the n-1 disks on the auxiliary to the target using the source as the auxiliary.
Program:
if(disks == 1):
return
output
Algorithm:
Program:
def recur_factorial(n):
if n == 1:
return n
else:
return n*recur_factorial(n-1)
num = 5
if num < 0:
elif num == 0:
else:
output:
Algorithm:
Program:
def recur_fibo(n):
if n <= 1:
return n
else:
return(recur_fibo(n-1) + recur_fibo(n-2))
nterms = 5
if nterms <= 0:
else:
print("Fibonacci sequence:")
for i in range(nterms):
print(recur_fibo(i))
output
Fibonacci sequence:
0
1
1
2
3
Algorithm:
1. Create two function: pascal() and pascal triangle(), give the number as argument
Program:
import sys
def pascal(col,row):
return 1
else:
def PascalTriangle(num):
for r in range(num):
for c in range(r+1):
sys.stdout.write(str(pascal(c,r))+' ')
sys.stdout.write('\n')
PascalTriangle(4)
Output
1
1 1
1 2 1
1 3 3 1
Result:
Thus the program is successfully executed
Downloaded by vinoline v ([email protected])
lOMoARcPSD|37194134
EX NO:-
Aim:
Algorithm:
Program:
class Student:
self.name = name
self.rollno = rollno
self.m1 = m1
self.m2 = m2
ls.append(ob)
print("\n")
if(ls[i].rollno == rn):
return i
i = obj.search(rn)
del ls[i]
i = obj.search(rn)
roll = No
ls[i].rollno = roll;
ls =[]
obj = Student('', 0, 0, 0)
# ch = int(input("Enter choice:"))
# if(ch == 1):
# elif(ch == 2):
print("\n")
print("\nList of Students\n")
obj.display(ls[i])
# elif(ch == 3):
s = obj.search(2)
obj.display(ls[s])
# elif(ch == 4):
obj.delete(2)
obj.display(ls[i])
# elif(ch == 5):
obj.update(3, 2)
obj.display(ls[i])
# else:
print("")
output:
Operations used,
List of Students
Name : A
RollNo : 1
Marks1 : 100
Marks2 : 100
Name : B
RollNo : 2
Marks1 : 90
Marks2 : 90
Name : C
RollNo : 3
Marks1 : 80
Marks2 : 80
Student Found,
Name : B
RollNo : 2
Marks1 : 90
Marks2 : 90
2
List after deletion
Name : A
RollNo : 1
Marks1 : 100
Marks2 : 100
Name : C
RollNo : 3
Marks1 : 80
Marks2 : 80
2
List after updation
Name : A
RollNo : 1
Marks1 : 100
Marks2 : 100
Name : C
RollNo : 2
Marks1 : 80
Marks2 : 8
RESULT
Thus the program is successfully executed
EX NO:-
Aim:
To write a program for linked list implementation of single, double and circular linked list
Algorithm:
1. Defining the Node class which actually holds the data as well as the next element link
2. Defining the Linked List class
3. Initializing the Linked List constructor with head variable
4. Defining the insert() method which is used to add elements to the Circular Singly Linked List
a. Checking whether or not the Linked List empty
b. Adding a Node to the beginning of the Linked List
c. Adding a Node to the end of the Linked List
d. Adding a Node in the middle of the Linked List
5. Defining the delete() method which is used to delete elements from the Circular Singly
Linked List
a. Checking whether or not the Linked List is empty or not, or deleting the last element
in the Linked List
b. Deleting the first element of the Linked List
c. Deleting the last element of the Linked List
d. Deleting an element by position or by value
6. Defining the display() method which is used to present the Circular Singly Linked List in a
user-comprehendible form
Program:
class Node:
self.dataval = dataval
self.nextval = None
class SLinkedList:
self.headval = None
def AtBegining(self,newdata):
NewNode = Node(newdata)
NewNode.nextval = self.headval
self.headval = NewNode
NewNode = Node(newdata)
if self.headval is None:
self.headval = NewNode
return
laste = self.headval
while(laste.nextval):
laste = laste.nextval
laste.nextval=NewNode
def Inbetween(self,middle_node,newdata):
if middle_node is None:
return
NewNode = Node(newdata)
NewNode.nextval = middle_node.nextval
middle_node.nextval = NewNode
if self.headval is None:
return
n = self.headval
if n.dataval == x:
print("Item found")
return True
n = n.nextval
return False
def getCount(self):
while (temp):
count += 1
temp = temp.nextval
return count
HeadVal = self.headval
if (HeadVal.dataval == Removekey):
self.headval = HeadVal.nextval
HeadVal = None
return
if HeadVal.dataval == Removekey:
break
prev = HeadVal
HeadVal = HeadVal.nextval
if (HeadVal == None):
return
prev.nextval = HeadVal.nextval
HeadVal = None
def listprint(self):
printval = self.headval
print (printval.dataval)
printval = printval.nextval
list = SLinkedList()
list.headval = Node("1")
e2 = Node("2")
e3 = Node("3")
list.headval.nextval = e2
e2.nextval = e3
list.AtBegining("4")
list.AtEnd("5")
list.Inbetween(list.headval.nextval,"6")
list.search_item("3")
list.RemoveNode("2")
list.listprint()
output:
Item found
Count of nodes is : 6
4
1
6
2
3
5
after removing
4
1
6
3
5
class Node:
self.item = data
self.nref = None
self.pref = None
class DoublyLinkedList:
self.start_node = None
if self.start_node is None:
new_node = Node(data)
self.start_node = new_node
else:
if self.start_node is None:
new_node = Node(data)
self.start_node = new_node
print("node inserted")
return
new_node = Node(data)
new_node.nref = self.start_node
self.start_node.pref = new_node
self.start_node = new_node
if self.start_node is None:
new_node = Node(data)
self.start_node = new_node
return
n = self.start_node
n = n.nref
new_node = Node(data)
n.nref = new_node
new_node.pref = n
if self.start_node is None:
print("List is empty")
return
else:
n = self.start_node
if n.item == x:
break
n = n.nref
if n is None:
else:
new_node = Node(data)
new_node.pref = n
new_node.nref = n.nref
n.nref.prev = new_node
n.nref = new_node
if self.start_node is None:
print("List is empty")
return
else:
n = self.start_node
if n.item == x:
break
n = n.nref
if n is None:
else:
new_node = Node(data)
new_node.nref = n
new_node.pref = n.pref
n.pref.nref = new_node
n.pref = new_node
def traverse_list(self):
if self.start_node is None:
return
else:
n = self.start_node
n = n.nref
def delete_at_start(self):
if self.start_node is None:
return
if self.start_node.nref is None:
self.start_node = None
return
self.start_node = self.start_node.nref
self.start_prev = None;
def delete_at_end(self):
if self.start_node is None:
return
if self.start_node.nref is None:
self.start_node = None
return
n = self.start_node
n = n.nref
n.pref.nref = None
if self.start_node is None:
return
if self.start_node.nref is None:
if self.start_node.item == x:
self.start_node = None
else:
return
if self.start_node.item == x:
self.start_node = self.start_node.nref
self.start_node.pref = None
return
n = self.start_node
if n.item == x:
break;
n = n.nref
n.pref.nref = n.nref
n.nref.pref = n.pref
else:
if n.item == x:
n.pref.nref = None
else:
new_linked_list = DoublyLinkedList()
new_linked_list.insert_in_emptylist(50)
new_linked_list.insert_at_start(10)
new_linked_list.insert_at_start(5)
print(new_linked_list.traverse_list())
new_linked_list.insert_at_end(29)
new_linked_list.insert_at_end(39)
print(new_linked_list.traverse_list())
new_linked_list.insert_after_item(50, 65)
print(new_linked_list.traverse_list())
new_linked_list.insert_before_item(29, 100)
print(new_linked_list.traverse_list())
new_linked_list.delete_at_start()
print(new_linked_list.traverse_list())
new_linked_list.delete_at_end()
print(new_linked_list.traverse_list())
new_linked_list.delete_element_by_value(65)
print(new_linked_list.traverse_list())
output:
5
10
50
None
5
10
50
29
39
None
5
10
50
65
29
39
None
5
10
50
100
29
39
None
10
50
100
29
39
None
10
50
100
29
None
Element not found
10
50
100
29
None
class Node:
self.data = data
self.next = None
class CircularLinkedList:
self.head = None
if self.head is None:
return None
current = self.head
for i in range(index):
current = current.next
if current == self.head:
return None
return current
if self.head is None:
return None
current = self.head
current = current.next
return current
new_node.next = ref_node.next
ref_node.next = new_node
prev_node = self.get_prev_node(ref_node)
self.insert_after(prev_node, new_node)
if self.head is None:
self.head = new_node
new_node.next = new_node
else:
self.insert_before(self.head, new_node)
self.insert_at_end(new_node)
self.head = new_node
if self.head.next == self.head:
self.head = None
else:
prev_node = self.get_prev_node(node)
prev_node.next = node.next
if self.head == node:
self.head = node.next
def display(self):
if self.head is None:
return
current = self.head
while True:
current = current.next
if current == self.head:
break
a_cllist = CircularLinkedList()
print('Menu')
print('remove <index>')
print('quit')
while True:
a_cllist.display()
print()
operation = do[0].strip().lower()
if operation == 'insert':
data = int(do[1])
position = do[3].strip().lower()
new_node = Node(data)
suboperation = do[2].strip().lower()
if suboperation == 'at':
if position == 'beg':
a_cllist.insert_at_beg(new_node)
a_cllist.insert_at_end(new_node)
else:
index = int(position)
ref_node = a_cllist.get_node(index)
if ref_node is None:
continue
if suboperation == 'after':
a_cllist.insert_after(ref_node, new_node)
a_cllist.insert_before(ref_node, new_node)
index = int(do[1])
node = a_cllist.get_node(index)
if node is None:
continue
a_cllist.remove(node)
break
output:
Menu
insert <data> after <index>
insert <data> before <index>
insert <data> at beg
insert <data> at end
remove <index>
quit
The list:
What would you like to do? insert 5 at beg
The list: 5
What would you like to do? insert 4 at beg
The list: 4 5
What would you like to do? insert 9 at end
The list: 4 5 9
What would you like to do? insert 6 after 1
The list: 4 5 6 9
What would you like to do? insert 7 after 6
No such index.
The list: 4 5 6 9
What would you like to do? insert 8 before 2
The list: 4 5 8 6 9
What would you like to do? remove 4
The list: 4 5 8 6
What would you like to do? remove 7
No such index.
The list: 4 5 8 6
What would you like to do? remove 0
The list: 5 8 6
What would you like to do? remove 1
The list: 5 6
What would you like to do? quit
class Node:
self.data = data
self.next = None
self.prev = None
class CircularDoublyLinkedList:
self.first = None
current = self.first
for i in range(index):
current = current.next
if current == self.first:
return None
return current
new_node.prev = ref_node
new_node.next = ref_node.next
new_node.next.prev = new_node
ref_node.next = new_node
self.insert_after(ref_node.prev, new_node)
if self.first is None:
self.first = new_node
new_node.next = new_node
new_node.prev = new_node
else:
self.insert_after(self.first.prev, new_node)
self.insert_at_end(new_node)
self.first = new_node
if self.first.next == self.first:
self.first = None
else:
node.prev.next = node.next
node.next.prev = node.prev
if self.first == node:
self.first = node.next
def display(self):
if self.first is None:
return
current = self.first
while True:
current = current.next
if current == self.first:
break
a_cdllist = CircularDoublyLinkedList()
print('Menu')
print('remove <index>')
print('quit')
while True:
a_cdllist.display()
print()
operation = do[0].strip().lower()
if operation == 'insert':
data = int(do[1])
position = do[3].strip().lower()
new_node = Node(data)
suboperation = do[2].strip().lower()
if suboperation == 'at':
if position == 'beg':
a_cdllist.insert_at_beg(new_node)
a_cdllist.insert_at_end(new_node)
else:
index = int(position)
ref_node = a_cdllist.get_node(index)
if ref_node is None:
continue
if suboperation == 'after':
a_cdllist.insert_after(ref_node, new_node)
a_cdllist.insert_before(ref_node, new_node)
index = int(do[1])
node = a_cdllist.get_node(index)
if node is None:
continue
a_cdllist.remove(node)
break
output:
Menu
insert <data> after <index>
insert <data> before <index>
insert <data> at beg
insert <data> at end
remove <index>
quit
The list:
What would you like to do? insert 1 at beg
The list: 1
What would you like to do? insert 3 at end
The list: 1 3
What would you like to do? insert 2 before 1
The list: 1 2 3
What would you like to do? insert 4 after 2
The list: 1 2 3 4
What would you like to do? insert 0 at beg
The list: 0 1 2 3 4
What would you like to do? remove 2
The list: 0 1 3 4
What would you like to do? quit
Result:
EX NO:-
Aim:
To write a program to implement stack and queue ADTs using linked list
5a.Algorithm
Program:
class Node:
self.data = data
self.next = next
class Stack:
self.top = None
if self.top is None:
return
def pop(self):
if self.top is None:
return
temp = self.top
self.top = self.top.next
temp.next = None
return temp.data
def peek(self):
return self.top.data
def clearstack(self):
self.top = None
def emptystack(self):
if self.top is None:
return True
return False
def display(self):
itr = self.top
while itr:
itr = itr.next
print(sstr)
stack = Stack()
stack.push(10)
stack.push(20)
stack.push(40)
stack.peek()
stack.display()
stack.pop()
stack.push(30)
#stack.display()
#stack.clearstack()
#stack.display()
Output:
push operation
40-->20-->10-->
pop
30-->20-->10-->
stack is empty
5b.Algorithm:
1. Create a newNode with the given value and set the node's pointer to NULL.
2. Check whether queue is EMPTY.
3. If it is EMPTY, set FRONT and REAR to newNode.
4. Else, set the pointer of REAR to newNode and make REAR as the newNode.
5. Check if the queue is EMPTY.
6. If it is EMPTY, then display "EMPTY QUEUE" and exit.
7. Else, create a temporary node and set it to FRONT.
8. Make the next node as FRONT and delete the temporary node.
9. Display the nodes in queue
Program:
class Node:
class Queue:
if self.rear is None:
return
self.rear.next.prev = self.rear
self.rear = self.rear.next
def dequeue(self):
if self.front is None:
temp = self.front.data
self.front = self.front.next
if self.front is None:
self.rear = None
return
self.front.prev = None
return temp
def clearqueue(self):
def emptyqueue(self):
if self.front is None:
return True
return False
def display(self):
itr = self.front
while itr:
itr = itr.next
print(sstr)
queue = Queue()
queue.enqueue(10)
queue.enqueue(20)
queue.enqueue(30)
queue.display()
queue.dequeue()
#queue.dequeue()
#queue.dequeue()
queue.display()
queue.enqueue(40)
queue.enqueue(50)
queue.enqueue(60)
queue.display()
queue.clearqueue()
queue.display()
output:
insertion
10-->20-->30-->
after deletion
20-->30-->
20-->30-->40-->50-->60-->
queue is empty
Result:
Thus the program is executed successfully
Downloaded by vinoline v ([email protected])
lOMoARcPSD|37194134
EX NO:-
Aim:
a) Matrix manipulation(list)
Algorithm:
Program:
A=[]
for i in range(n):
row=[]
for j in range(n):
row.append(int(input()))
A. append(row)
print(A)
for i in range(n):
for j in range(n):
print()
B=[]
for i in range(n):
row=[]
for j in range(n):
row.append(int(input()))
B. append(row)
print(B)
for i in range(n):
for j in range(n):
print()
for i in range(n):
for j in range(len(A[0])):
for r in result:
for i in range(n):
for j in range(len(A[0])):
for r in result:
for i in range(n):
for j in range(len(A[0])):
for r in result:
for i in range(n):
for j in range(n):
result[i][j] = result[j][i]
for r in result:
for i in range(n):
for j in range(len(A[0])):
for r in result:
output
1 2 3
4 5 6
7 8 9
Enter N for N x N matrix : 3
Enter the element ::>
1
2
3
4
5
6
7
8
9
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Display Array In Matrix Form
1 2 3
4 5 6
7 8 9
Resultant Matrix is ::>
Resultant Matrix is ::> [2, 4, 6]
Resultant Matrix is ::> [8, 10, 12]
Resultant Matrix is ::> [14, 16, 18]
Resultant Matrix is ::>
Resultant Matrix is ::> [0, 0, 0]
Resultant Matrix is ::> [0, 0, 0]
Resultant Matrix is ::> [0, 0, 0]
Resultant Matrix is ::>
Resultant Matrix is ::> [1, 4, 9]
Resultant Matrix is ::> [16, 25, 36]
Resultant Matrix is ::> [49, 64, 81]
Resultant Matrix is ::> [1, 16, 49]
Resultant Matrix is ::> [16, 25, 64]
Resultant Matrix is ::> [49, 64, 81]
Resultant Matrix is ::>
Resultant Matrix is ::> [0, 0, 0]
Resultant Matrix is ::> [0, 0, 0]
Resultant Matrix is ::> [0, 0, 0]
b) Applications of stack
Infix to postfix
Algorithm:
5. If the scanned character is an ‘)’, pop the stack and output it until a ‘(‘ is encountered, and
discard both the parenthesis.
6. Repeat steps 2-6 until infix expression is scanned.
7. Print the output
8. Pop and output from the stack until it is not empty.
Program:
def infix_to_postfix(expression):
for ch in expression:
if ch not in OPERATORS:
output+= ch
elif ch=='(':
stack.append('(')
elif ch==')':
output+=stack.pop()
stack.pop()
else:
output+=stack.pop()
stack.append(ch)
while stack:
output+=stack.pop()
return output
output:
Algorithm:
Program:
class Queue:
self.s1 = deque()
self.s2 = deque()
while len(self.s1):
self.s2.append(self.s1.pop())
self.s1.append(data)
while len(self.s2):
self.s1.append(self.s2.pop())
def dequeue(self):
if not self.s1:
print("Underflow!!")
exit(0)
return self.s1.pop()
= [1, 2, 3, 4, 5]
q = Queue()
q.enqueue(key)
print(q.dequeue())
print(q.dequeue())
print(q.dequeue())
output:
1
2
3
4
5
Result:
EX NO :-
Aim:
1.Bubble sort
Algorithm
Program
def bubbleSort(arr):
n = len(arr)
for i in range(n-1):
print(arr)
arr = [5,3,8,6,7,2]
bubbleSort(arr)
for i in range(len(arr)):
output:
2) selection sort
Algorithm:
Program:
import sys
A = [5,3,8,6,7,2]
for i in range(len(A)):
min_idx = i
min_idx = j
print(A)
for i in range(len(A)):
print("%d" %A[i]),
output:
Sorted array
[2, 3, 5, 6, 7, 8]
3) insertion sort
Algorithm
Program:
def insertionSort(arr):
key = arr[i]
j=i
j = i-1
arr[j+1] = arr[j]
j -= 1
arr[j+1] = key
print(arr)
insertionSort(arr)
for i in range(len(arr)):
output:
4) quick sort
Algorithm:
1. Select the Pivot Element as first, last, random and median element
2. Rearrange the Array
a. A pointer is fixed at the pivot element. The pivot element is compared with the
elements beginning from the first index.
b. If the element is greater than the pivot element, a second pointer is set for that
element.
c. Now, pivot is compared with other elements. If an element smaller than the pivot
element is reached, the smaller element is swapped with the greater element found
earlier.
d. Again, the process is repeated to set the next greater element as the second pointer.
And, swap it with another smaller element.
e. The process goes on until the second last element is reached.
f. Finally, the pivot element is swapped with the second pointer
3. Divide Subarrays
a. Pivot elements are again chosen for the left and the right sub-parts separately.
And, step 2 is repeated.
b. The subarrays are divided until each subarray is formed of a single element. At this
point, the array is sorted.
Program:
def pivot_place(list1,first,last):
pivot = list1[first]
left = first+1
right = last
while True:
left = left+1
right = right-1
break
else:
return right
list1 = [56,26,93,17,31,44]
n=len(list1)
quicksort(list1, 0, n-1)
print(list1)
output:
sorted array is
[17, 26, 31, 44, 56, 93]
def pivot_place(list1,first,last):
pivot = list1[last]
left = first
right = last-1
while True:
left = left+1
right = right-1
break
else:
return left
list1 = [56,26,93,17,31,44]
n=len(list1)
quicksort(list1, 0, n-1)
print(list1)
output:
sorted array is
[17, 26, 31, 44, 56, 93]
import random
def pivot_place(list1,first,last):
pivot = list1[last]
left = first
right = last-1
while True:
left = left+1
right = right-1
break
else:
return left
list1 = [56,26,93,17,31,44]
n=len(list1)
quicksort(list1, 0, n-1)
print(list1)
output:
sorted array is
[17, 26, 31, 44, 56, 93]
import statistics
def pivot_place(list1,first,last):
low = list1[first]
high = list1[last]
mid = (first+last)//2
if pivot_val == low:
pindex = first
pindex = last
else:
pindex = mid
pivot = list1[last]
left = first
right = last-1
while True:
left = left+1
right = right-1
break
else:
return left
list1 = [56,26,93,17,31,44]
n=len(list1)
quicksort(list1, 0, n-1)
print(list1)
Output:
sorted array is
[17, 26, 31, 44, 56, 93]
5) merge sort
Algorithm:
Program:
def mergeSort(arr):
if len(arr) > 1:
mid = len(arr)//2
L = arr[:mid]
R = arr[mid:]
mergeSort(L)
mergeSort(R)
i=j=k=0
arr[k] = L[i]
i += 1
else:
arr[k] = R[j]
j += 1
k += 1
arr[k] = L[i]
i += 1
k += 1
arr[k] = R[j]
j += 1
k += 1
def printList(arr):
for i in range(len(arr)):
print()
printList(arr)
mergeSort(arr)
printList(arr)
output:
Given array is
38 27 43 3 9 82 10
Sorted array is:
3 9 10 27 38 43 82
6) LINEAR SEARCH
Algorithm:
Program:
if obj[i] == item:
return i
return -1
arr=[1,2,3,4,5,6,7,8]
x=4
result=linear_search(arr,x)
if result==-1:
else:
Output:
7) BINARY SEARCH
Algorithm:
Program:
if arr[mid] == x:
return mid
else:
else:
return -1
arr = [ 2, 3, 4, 10, 40 ]
x = 40
if result != -1:
else:
output:
Result
EX NO:-
8.IMPLEMENTATION OF HASH TABLES
DATE:-
Aim:
Algorithm:
Program:
class hashTable:
self.elementCount = 0
self.comparisons = 0
def isFull(self):
if self.elementCount == self.size:
return True
else:
return False
if self.isFull():
return False
isStored = False
position = self.hashFunction(element)
if self.table[position] == 0:
self.table[position] = element
isStored = True
self.elementCount += 1
else:
print("Collision has occured for element " + str(element) + " at position " + str(position) + "
finding new Position.")
while self.table[position] != 0:
position += 1
position = 0
self.table[position] = element
isStored = True
self.elementCount += 1
return isStored
found = False
position = self.hashFunction(element)
self.comparisons += 1
if(self.table[position] == element):
return position
isFound = True
else:
temp = position - 1
if self.table[position] != element:
position += 1
self.comparisons += 1
else:
return position
position = temp
if self.table[position] != element:
position -= 1
self.comparisons += 1
else:
return position
if not found:
return False
position = self.search(element)
self.table[position] = 0
self.elementCount -= 1
else:
return
def display(self):
print("\n")
for i in range(self.size):
table1 = hashTable()
table1.insert(89)
table1.insert(18)
table1.insert(49)
table1.insert(58)
table1.insert(9)
table1.display()
print()
print()
table1.remove(18)
table1.display()
output
0 = 49
1 = 58
2 = 9
3 = 0
4 = 0
5 = 0
6 = 0
7 = 0
8 = 18
9 = 89
The number of element is the Table are : 5
Element 18 is Deleted
0 = 49
1 = 58
2 = 9
3 = 0
4 = 0
5 = 0
6 = 0
7 = 0
8 = 0
9 = 89
The number of element is the Table are : 4
Algorithm:
Program:
class hashTable:
self.elementCount = 0
self.comparisons = 0
def isFull(self):
if self.elementCount == self.size:
return True
else:
return False
posFound = False
limit = 50
i=1
if self.table[newPosition] == 0:
posFound = True
break
else:
i += 1
if self.isFull():
return False
isStored = False
position = self.hashFunction(element)
if self.table[position] == 0:
self.table[position] = element
isStored = True
self.elementCount += 1
else:
print("Collision has occured for element " + str(element) + " at position " + str(position) + "
finding new Position.")
if isStored:
self.table[position] = element
self.elementCount += 1
return isStored
found = False
position = self.hashFunction(element)
self.comparisons += 1
if(self.table[position] == element):
return position
else:
limit = 50
i=1
newPosition = position
self.comparisons += 1
if self.table[newPosition] == element:
found = True
break
elif self.table[newPosition] == 0:
found = False
break
else:
i += 1
if found:
return newPosition
else:
return found
position = self.search(element)
self.table[position] = 0
self.elementCount -= 1
else:
return
def display(self):
print("\n")
for i in range(self.size):
table1 = hashTable()
table1.insert(89)
table1.insert(18)
table1.insert(49)
table1.insert(58)
table1.insert(9)
table1.display()
print()
print()
#table1.remove(90)
table1.remove(18)
table1.display()
output:
0 = 49
1 = 0
2 = 58
3 = 9
4 = 0
5 = 0
6 = 0
7 = 0
8 = 18
9 = 89
The number of element is the Table are : 5
Element 18 is Deleted
0 = 49
1 = 0
2 = 58
3 = 9
4 = 0
5 = 0
6 = 0
7 = 0
8 = 0
9 = 89
The number of element is the Table are : 4
Algorithm:
Program:
class doubleHashTable:
self.num = 7
self.elementCount = 0
self.comparisons = 0
def isFull(self):
if self.elementCount == self.size:
return True
else:
return False
posFound = False
limit = 50
i=1
if self.table[newPosition] == 0:
posFound = True
break
else:
i += 1
if self.isFull():
return False
posFound = False
position = self.h1(element)
if self.table[position] == 0:
self.table[position] = element
isStored = True
self.elementCount += 1
else:
print("Collision has occured for element " + str(element) + " at position " + str(position) + "
finding new Position.")
if posFound:
self.table[position] = element
self.elementCount += 1
return posFound
found = False
position = self.h1(element)
self.comparisons += 1
if(self.table[position] == element):
return position
else:
limit = 50
i=1
newPosition = position
self.comparisons += 1
if self.table[position] == element
found = True
break
elif self.table[position] == 0:
found = False
break
else:
i += 1
if found:
return position
else:
return found
position = self.search(element)
self.table[position] = 0
self.elementCount -= 1
else:
return
def display(self):
print("\n")
for i in range(self.size):
table1 = doubleHashTable()
table1.insert(89)
table1.insert(18)
table1.insert(49)
table1.insert(58)
table1.insert(9)
table1.display()
print()
print()
table1.remove(18)
table1.display()
output:
0 = 0
1 = 0
2 = 0
3 = 58
4 = 9
5 = 0
6 = 49
7 = 0
8 = 18
9 = 89
The number of element is the Table are : 5
Element 18 is Deleted
0 = 0
1 = 0
2 = 0
3 = 58
4 = 9
5 = 0
6 = 49
7 = 0
8 = 0
9 = 89
The number of element is the Table are : 4
Result:
EX NO:-
Aim:
To write a program for to implement tree representation and tree traversal algorithm
9a.Array representation
Algorithm:
Program:
tree = [None] * 20
def root(key):
if tree[0] != None:
else:
tree[0] = key
if tree[parent] == None:
else:
tree[(parent * 2) + 1] = key
if tree[parent] == None:
else:
tree[(parent * 2) + 2] = key
def print_tree():
for i in range(20):
if tree[i] != None:
print(tree[i], end="")
else:
print("-", end="")
print()
root('3')
set_left('5', 0)
set_right('9', 0)
set_left('6', 1)
set_right('8', 1)
set_left('20', 2)
set_right('10', 2)
set_left('9', 5)
print_tree()
output
Array representation
359682010 9
9b.linkedlist representation
Algorithm:
Program:
class Node:
self.data = data;
self.left = None;
self.right = None;
class BinaryTree:
self.root = None;
newNode = Node(data);
if(self.root == None):
self.root = newNode;
return;
else:
queue = [];
queue.append(self.root);
while(True):
node = queue.pop(0);
queue.append(node.left);
queue.append(node.right);
else:
if(node.left == None):
node.left = newNode;
queue.append(node.left);
else:
node.right = newNode;
queue.append(node.right);
break;
if(self.root == None):
print("Tree is empty");
return;
else:
if(node.left != None):
self.inorderTraversal(node.left);
print(node.data),
if(node.right!= None):
self.inorderTraversal(node.right);
bt = BinaryTree();
bt.insertNode(1);
bt.inorderTraversal(bt.root);
bt.insertNode(2);
bt.insertNode(3);
bt.inorderTraversal(bt.root);
bt.insertNode(4);
bt.insertNode(5);
bt.inorderTraversal(bt.root);
bt.insertNode(6);
bt.insertNode(7);
bt.inorderTraversal(bt.root);
output:
Algorithm:
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()
print( self.data),
if self.right:
self.right.PrintTree()
res = []
if root:
res = self.inorderTraversal(root.left)
res.append(root.data)
return res
res = []
if root:
res.append(root.data)
return res
res = []
if root:
res = self.PostorderTraversal(root.left)
res.append(root.data)
return res
root = Node(27)
root.insert(14)
root.insert(35)
root.insert(10)
root.insert(19)
root.insert(31)
root.insert(42)
print(root.inorderTraversal(root))
print(root.PreorderTraversal(root))
print(root.PostorderTraversal(root))
output
Inorder traversal
[10, 14, 19, 27, 31, 35, 42]
preorder traversal
[27, 14, 10, 19, 35, 31, 42]
postorder traversal
[10, 19, 14, 31, 42, 35, 27]
Result
EX NO:-
Aim:
Algorithm:
Program:
class Node:
self.key = key
self.left = None
self.right = None
def inorder(root):
inorder(root.left)
inorder(root.right)
if node is None:
return Node(key)
else:
return node
def minValueNode(node):
current = node
current = current.left
return current
if root is None:
return root
else:
if root.left is None:
temp = root.right
root = None
return temp
temp = root.left
root = None
return temp
temp = minValueNode(root.right)
root.key = temp.key
return root
root = None
root = insert(root, 8)
root = insert(root, 3)
root = insert(root, 1)
root = insert(root, 6)
root = insert(root, 7)
root = insert(root, 4)
inorder(root)
print("\nDelete 4")
root = deleteNode(root, 4)
inorder(root)
print("\nDelete 6")
root = deleteNode(root, 6)
inorder(root)
print("\nDelete 3")
root = deleteNode(root, 3)
inorder(root)
output:
Inorder traversal: 1-> 3-> 4-> 6-> 7-> 8-> 10-> 14->
Delete 4
Inorder traversal: 1-> 3-> 6-> 7-> 8-> 10-> 14->
Delete 6
Inorder traversal: 1-> 3-> 7-> 8-> 10-> 14->
Delete 3
Inorder traversal: 1-> 7-> 8-> 10-> 14->
Algorithm:
Program:
import sys
class TreeNode(object):
self.key = key
self.left = None
self.right = None
self.height = 1
class AVLTree(object):
if not root:
return TreeNode(key)
else:
root.height = 1 + max(self.getHeight(root.left),
self.getHeight(root.right))
balanceFactor = self.getBalance(root)
if balanceFactor > 1:
return self.rightRotate(root)
else:
root.left = self.leftRotate(root.left)
return self.rightRotate(root)
return self.leftRotate(root)
else:
root.right = self.rightRotate(root.right)
return self.leftRotate(root)
return root
if not root:
return root
else:
if root.left is None:
temp = root.right
root = None
return temp
temp = root.left
root = None
return temp
temp = self.getMinValueNode(root.right)
root.key = temp.key
root.right = self.delete_node(root.right,
temp.key)
if root is None:
return root
root.height = 1 + max(self.getHeight(root.left),
self.getHeight(root.right))
balanceFactor = self.getBalance(root)
if balanceFactor > 1:
if self.getBalance(root.left) >= 0:
return self.rightRotate(root)
else:
root.left = self.leftRotate(root.left)
return self.rightRotate(root)
if self.getBalance(root.right) <= 0:
return self.leftRotate(root)
else:
root.right = self.rightRotate(root.right)
return self.leftRotate(root)
return root
y = z.right
T2 = y.left
y.left = z
z.right = T2
z.height = 1 + max(self.getHeight(z.left),
self.getHeight(z.right))
y.height = 1 + max(self.getHeight(y.left),
self.getHeight(y.right))
return y
y = z.left
T3 = y.right
y.right = z
z.left = T3
z.height = 1 + max(self.getHeight(z.left),
self.getHeight(z.right))
y.height = 1 + max(self.getHeight(y.left),
self.getHeight(y.right))
return y
if not root:
return 0
return root.height
if not root:
return 0
return root
return self.getMinValueNode(root.left)
if not root:
return
self.preOrder(root.left)
self.preOrder(root.right)
if currPtr != None:
sys.stdout.write(indent)
if last:
else:
print(currPtr.key)
myTree = AVLTree()
root = None
nums = [15,20,24,10,13,7,30,36,25]
key = 24
key = 20
key = 15
output:
R 13
L ------ 10
| L ------ 7
R 24
L ------ 20
| L------- 15
R 30
L------- 25
R 36
After Deletion:
R 13
L ------ 10
| L ------ 7
R 25
L ------ 20
| L------- 15
R 30
R------- 36
After Deletion:
R 13
L ------ 10
| L ------ 7
R 25
L ------ 15
R 30
R------- 36
After Deletion:
R 13
L ------ 10
| L ------ 7
R 30
L ------ 25
R 36
Result:
EX NO:-
Aim:
Program:
largest = i
l=2*i+1
r=2*i+2
largest = l
largest = r
if largest != i:
arr[i],arr[largest] = arr[largest],arr[i]
heapify(arr, n, largest)
size = len(array)
if size == 0:
array.append(newNum)
else:
array.append(newNum);
heapify(array, size, i)
size = len(array)
i=0
if num == array[i]:
break
array.remove(num)
heapify(array, len(array), i)
arr = []
insert(arr, 35)
insert(arr, 33)
insert(arr, 42)
insert(arr, 10)
insert(arr, 14)
insert(arr, 19)
insert(arr, 27)
insert(arr, 44)
insert(arr, 26)
deleteNode(arr, 44)
deleteNode(arr, 33)
output:
Max-Heap array: [44, 42, 35, 33, 14, 19, 27, 10, 26]
After deleting an element: [42, 33, 35, 26, 14, 19, 27, 10]
After deleting an element: [42, 26, 35, 10, 14, 19, 27]
program:
def min_heapify(A,k):
l = left(k)
r = right(k)
smallest = l
else:
smallest = k
smallest = r
if smallest != k:
min_heapify(A, smallest)
def left(k):
return 2 * k + 1
def right(k):
return 2 * k + 2
def build_min_heap(A):
n = int((len(A)//2)-1)
min_heapify(A,k)
A = [3,9,2,1,4,5]
build_min_heap(A)
print(A)
output:
Min heap:
[1, 3, 2, 9, 4, 5]
Result:
EX NO:-
12.Graph representation and Traversal algorithm
DATE:-
Aim:
Algorithm:
Program:
class AdjNode:
self.vertex = data
self.next = None
class Graph:
self.V = vertices
node = AdjNode(dest)
node.next = self.graph[src]
self.graph[src] = node
node = AdjNode(src)
node.next = self.graph[dest]
self.graph[dest] = node
def print_graph(self):
for i in range(self.V):
temp = self.graph[i]
while temp:
temp = temp.next
print(" \n")
V=5
graph = Graph(V)
graph.add_edge(0, 1)
graph.add_edge(0, 4)
graph.add_edge(1, 2)
graph.add_edge(1, 3)
graph.add_edge(1, 4)
graph.add_edge(2, 3)
graph.add_edge(3, 4)
graph.print_graph()
output
Algorithm:
Program:
class Graph:
n=0
self. n=x
self __ g[i][j]= 0
def displayAdjacencyMatrix(self):
print()
if(x == y):
else:
self _ g[y][x]= 1
self _ g[x][y]= 1
def addVertex(self):
self. n = self. n + 1;
if(x>self. n):
else:
while(x<self. n):
x=x+1
self. n = self. n - 1
obj = Graph(4);
obj.addEdge(0, 1);
obj.addEdge(0, 2);
obj.addEdge(1, 2);
obj.addEdge(2, 3);
obj.displayAdjacencyMatrix();
#obj.addVertex();
#obj.addEdge(4, 1);
#obj.addEdge(4, 3);
obj.displayAdjacencyMatrix();
obj.removeVertex(1);
obj.displayAdjacencyMatrix();
output
Adjacency Matrix:
0 1 1 0
1 0 1 0
1 1 0 1
0 0 1 0
Adjacency Matrix:
0 1 1 0
1 0 1 0
1 1 0 1
0 0 1 0
Adjacency Matrix:
0 1 0
1 0 1
0 1 0
Algorithm:
1. Start by putting any one of the graph's vertices at the back of a queue.
2. Take the front item of the queue and add it to the visited list.
3. Create a list of that vertex's adjacent nodes. Add the ones which aren't in the visited list to the
back of the queue.
4. Keep repeating steps 2 and 3 until the queue is empty.
Program 1:
graph = {
'5' : ['3','7'],
'3' : ['2', '4'],
'7' : ['8'],
'2' : [],
'4' : ['8'],
'8' : []
}
visited = []
queue = []
def bfs(visited, graph, node):
visited.append(node)
queue.append(node)
while queue:
m = queue.pop(0)
print (m, end = " ")
for neighbour in graph[m]:
if neighbour not in visited:
visited.append(neighbour)
queue.append(neighbour)
print("Following is the Breadth-First Search")
bfs(visited, graph, '5')
output:
program 2:
graph = {'A': ['B', 'C', 'E'],
'B': ['A','D', 'E'],
'C': ['A', 'F', 'G'],
'D': ['B'],
'E': ['A', 'B','D'],
'F': ['C'],
'G': ['C']}
def bfs_connected_component(graph, start):
explored = []
queue = [start]
while queue:
node = queue.pop(0)
if node not in explored:
explored.append(node)
neighbours = graph[node]
for neighbour in neighbours:
queue.append(neighbour)
return explored
bfs_connected_component(graph,'A')
output:
['A', 'B', 'C', 'E', 'D', 'F', 'G']
Algorithm:
1. Create a recursive function that takes the index of the node and a visited array.
2. Mark the current node as visited and print the node.
3. Traverse all the adjacent and unmarked nodes and call the recursive function with the index of
the adjacent node.
4. Run a loop from 0 to the number of vertices and check if the node is unvisited in the previous
DFS, call the recursive function with the current node.
Program:
def recursive_dfs(graph, source,path = []):
if source not in path:
path.append(source)
if source not in graph:
return path
for neighbour in graph[source]:
path = recursive_dfs(graph, neighbour, path)
return path
graph = {"A":["B","C", "D"],
"B":["E"],
"C":["F","G"],
"D":["H"],
"E":["I"],
"F":["J"]}
path = recursive_dfs(graph, "A")
print(" ".join(path))
output:
DFS
A B E I C F J G D H
Result:
EX NO:-
13.Single source shortest path algorithm
DATE:-
Aim:
To write a program to implement single source shortest path algorithm
Algorithm:
1. Start with a weighted graph
2. Choose a starting vertex and assign infinity path values to all other vertices
3. Go to each vertex and update its path length
4. If the path length of the adjacent vertex is lesser than new path length, don’t update it
5. Avoid updating path length of already visited vertices
6. After each iteration pick the unvisited vertiex with the least path length
7. Repeat until all verties have been visited
Program:
import heapq
def calculate_distances(graph, starting_vertex):
distances = {vertex: float('infinity') for vertex in graph}
distances[starting_vertex] = 0
pq = [(0, starting_vertex)]
while len(pq) > 0:
current_distance, current_vertex = heapq.heappop(pq)
if current_distance > distances[current_vertex]:
continue
for neighbor, weight in graph[current_vertex].items():
distance = current_distance + weight
if distance < distances[neighbor]:
distances[neighbor] = distance
heapq.heappush(pq, (distance, neighbor))
return distances
example_graph = {
'v1': {'v2': 2, 'v4': 1,},
'v2': {'v4': 3, 'v5': 10,},
'v3': {'v1': 4,},
'v4': {'v3': 2, 'v6': 8, 'v7': 4, 'v5': 2},
'v5': {'v7': 6,},
'v6': {'v3': 5,},
'v7': {'v6': 1,},
}
print(calculate_distances(example_graph, 'v1'))
output:
shortest path
Result:
EX NO:-
Algorithm:
1. Sort all the edges in non-decreasing order of their weight.
2. Pick the smallest edge.
3. Check if it forms a cycle with the spanning tree formed so far.
4. If cycle is not formed, include this edge. Else, discard it.
5. 3. Repeat step2 until there are (V-1) edges in the spanning tree.
self.parent[root2] = root1
self.rank[root1] += 1
print("\nEdges of minimum spanning tree in graph :", end=' ')
cost = 0
for edge in self.mst :
print("[" + str(edge.src) + "-" + str(edge.dst) + "](" + str(edge.weight) + ")", end = ' ')
cost += edge.weight
print("\nCost of minimum spanning tree : " +str(cost))
def main() :
num_nodes = 5
e1 = Edge(0, 1, 5)
e2 = Edge(0, 3, 6)
e3 = Edge(1, 2, 1)
e4 = Edge(1, 3, 3)
e5 = Edge(2, 3, 4)
e6 = Edge(2, 4, 6)
e7 = Edge(3, 4, 2)
g1 = Graph(num_nodes, [e1, e2, e3, e4, e5, e6, e7])
g1.KruskalMST()
if name == " main " :
main()
output:
PRIM’S ALGORITHM
Algorithm:
[0, 0, 0, 4, 6, 1, 0]]
selected = [0, 0, 0, 0, 0, 0, 0]
no_edge = 0
selected[0] = True
print("Edge : Weight\n")
while (no_edge < V - 1):
minimum = INF
x=0
y=0
for i in range(V):
if selected[i]:
for j in range(V):
if ((not selected[j]) and G[i][j]):
if minimum > G[i][j]:
minimum = G[i][j]
x=i
y=j
print(str(x) + "-" + str(y) + ":" + str(G[x][y]))
selected[y] = True
no_edge += 1
output:
Edge : Weight
0-3:1
0-1:2
3-2:2
3-6:4
6-5:1
6-4:6
Result: