DSA LAB RECORD
DSA LAB RECORD
TIRUVANNAMALAI
Velu Nagar,Tiruvannamalai
Nagar,Tiruvannamalai-606603
www.arunai.org
(Cyber Security)
REGULATION 2021
CD3281-DATA
DATA STRUCTURES AND ALGORITHMS LABORATORY
ACADEMIC YEAR:2023
YEAR:2023-2024(ODD SEMESTER)
ARUNAI ENGINEERING COLLLEGE
TIRUVANNAMALAI
TIRUVANNAMALAI-606 603
(CYBER SECURITY)
Certified that this is a bonafide record of work done by
Name :
University Reg:No :
Semester :
Branch :
Year :
Staff-in-charge
charge Head of the Department
Date:
Aim:
To write a python program to implement ADTS as python classes
Algorithm:
1. Select the structure chosen by the user as 1 for stack and 7 for queue.
2. If press 1, it will call class Stack.
3. It will keep on checking till n1 becomes 5.
If press 1, accept from the user values and it will store in the stack.
4. If press 2, it will remove value from the stack.
5. If press 3, it will show the size of the stack.
6. If press 4, it will show itens of the stack.
7. If press 2, it will call class Queue
8. Accept from the user 1. 1. enqueue 2. dequeue 3. size 4.display 5.exit
9. It will keep on checking till n1 becomes 5.
10. Il press 1, accept from the user values and it will store in the enqueue.
11. If press 2, it will perform dequeue and display the message dequeue done.
12. If press 3, it will show the size of the queue.
13. If press 4, it will show items of the queue.
1
Program:
class Stack:
def init (self):
self.items = []
def isEmpty(self):
return self.items == []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[len(self.items) - 1]
def size(self):
return len(self.items)
class Queue:
def init (self):
self.items = []
def isEmpty(self):
return self.items == []
def enqueue(self,item):
self.items.append(item)
def dequeue(self):
return self.items.pop(0)
def front(self):
return self.items[len(self.items)-1]
def size(self):
return len(self.items)
s=Stack()
print('Stack operation examples')
print(s.isEmpty())
s.push(5)
s.push('python')
print(s.peek())
s.push(True)
print(s.size())
print(s.isEmpty())
s.push(11.5)
print(s.pop())
2
print(s.pop())
print(s.size())
q=Queue()
print('Queue operation examples')
print(q.isEmpty())
q.enqueue(5)
q.enqueue('python')
print(q.front())
q.enqueue(True)
print(q.size())
print(q.isEmpty())
q.enqueue(11.5)
print(q.dequeue())
print(q.dequeue())
print(q.size())
3
OUTPUT:
Stack operation examples
True
python
3
False
11.5
True
2
Queue operation examples
True
python
3
False
5
python
2
Result:
4
Ex.No:2a Implement Tower of Hanoi Using Recursive Algorithm in Python
Date:
Aim:
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.
5
Program:
if(disks == 1):
return
6
Output
Result:
7
Ex.No:2b Implement Fibonacci Series Using Recursive Algorithm in Python
Date:
Aim:
Algorithm:
8
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))
9
Output
Fibonacci sequence:
0
1
1
2
3
Result:
10
Ex.No:2c Implement Factorial of a number Using Recursive Algorithm in Python
Date:
Aim:
Algorithm:
11
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:
12
Output:
Result:
13
Ex.No:3 Implement list adt using python arrays
Date:
Aim:
Algorithm:
14
Program:
class Student:
def init (self, name, rollno, m1, m2):
self.name = name
self.rollno = rollno
self.m1 = m1
self.m2 = m2
def accept(self, Name, Rollno, marks1, marks2 ):
ob = Student(Name, Rollno, marks1, marks2 )
ls.append(ob)
def display(self, ob):
print("Name : ", ob.name)
print("RollNo : ", ob.rollno)
print("Marks1 : ", ob.m1)
print("Marks2 : ", ob.m2)
print("\n")
def search(self, rn):
for i in range(ls. len ()):
if(ls[i].rollno == rn):
return i
def delete(self, rn):
i = obj.search(rn)
del ls[i]
def update(self, rn, No):
i = obj.search(rn)
roll = No
ls[i].rollno = roll;
ls =[]
15
obj = Student('', 0, 0, 0)
print("\nOperations used, ")
print("\n1.Accept Student details\n2.Display Student Details\n"
"3.Search Details of a Student\n4.Delete Details of Student"
print("")
17
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
18
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
19
Ex.No:4a Implementation of Singly Linked List
Date:
Aim:
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 Singly Linked List
a. Checking whether or not the Linked List is 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 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 Singly Linked List in a
user-comprehendible form
20
Program:
class Node:
def init (self, dataval=None):
self.dataval = dataval
self.nextval = None
class SLinkedList:
def init (self):
self.headval = None
def AtBegining(self,newdata):
NewNode = Node(newdata)
NewNode.nextval = self.headval
self.headval = NewNode
def AtEnd(self, newdata):
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:
print("The mentioned node is absent")
return
NewNode = Node(newdata)
21
ewNode.nextval = middle_node.nextval
middle_node.nextval = NewNode
def search_item(self, x):
if self.headval is None:
print("List has no elements")
return
n = self.headval
while n is not None:
if n.dataval == x:
print("Item found")
return True
n = n.nextval
print("item not found")
return False
def getCount(self):
temp = self.headval # Initialise temp
count = 0 # Initialise count
while (temp):
count += 1
temp = temp.nextval
return count
def RemoveNode(self, Removekey):
HeadVal = self.headval
if (HeadVal is not None):
if (HeadVal.dataval == Removekey):
self.headval = HeadVal.nextval
HeadVal = None
return
22
while (HeadVal is not None):
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
while printval is not None:
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")
print ("Count of nodes is :",list.getCount())
list.RemoveNode("2")
list.listprint()
23
Output:
Item found
Count of nodes is : 6
4
1
6
2
3
5
after removing
4
1
6
3
5
Result:
24
Ex.No:4b Implementation of Doubly Linked List
Date:
Aim:
Algorithm:
1. Defining the Node class which actually holds the data, previous and 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 doubly Linked List
e. Checking whether or not the Linked List is empty
f. Adding a Node to the beginning of the Linked List
g. Adding a Node to the end of the Linked List
h. Adding a Node in the middle of the Linked List
5. Defining the delete() method which is used to delete elements from the doubly 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 doubly Linked List in a
user-comprehendible form
25
Program:
class Node:
def init (self, data):
self.item = data
self.nref = None
self.pref = None
class DoublyLinkedList:
def init (self):
self.start_node = None
def insert_in_emptylist(self, data):
if self.start_node is None:
new_node = Node(data)
self.start_node = new_node
else:
print("list is not empty")
def insert_at_start(self, data):
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
def insert_at_end(self, data):
26
if self.start_node is None:
new_node = Node(data)
self.start_node = new_node
return
n = self.start_node
while n.nref is not None:
n = n.nref
new_node = Node(data)
n.nref = new_node
new_node.pref = n
def insert_after_item(self, x, data):
if self.start_node is None:
print("List is empty")
return
else:
n = self.start_node
while n is not None:
if n.item == x:
break
n = n.nref
if n is None:
print("item not in the list")
else:
new_node = Node(data)
new_node.pref = n
new_node.nref = n.nref
if n.nref is not None:
n.nref.prev = new_node
27
n.nref = new_node
def insert_before_item(self, x, data):
if self.start_node is None:
print("List is empty")
return
else:
n = self.start_node
while n is not None:
if n.item == x:
break
n = n.nref
if n is None:
print("item not in the list")
else:
new_node = Node(data)
new_node.nref = n
new_node.pref = n.pref
if n.pref is not None:
n.pref.nref = new_node
n.pref = new_node
def traverse_list(self):
if self.start_node is None:
print("List has no element")
return
else:
n = self.start_node
while n is not None:
print(n.item , " ")
28
n = n.nref
def delete_at_start(self):
if self.start_node is None:
print("The list has no element to delete")
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:
print("The list has no element to delete")
return
if self.start_node.nref is None:
self.start_node = None
return
n = self.start_node
while n.nref is not None:
n = n.nref
n.pref.nref = None
def delete_element_by_value(self, x):
if self.start_node is None:
print("The list has no element to delete")
return
if self.start_node.nref is None:
if self.start_node.item == x:
self.start_node = None
29
else:
print("Item not found")
return
if self.start_node.item == x:
self.start_node = self.start_node.nref
self.start_node.pref = None
return
n = self.start_node
while n.nref is not None:
if n.item == x:
break;
n = n.nref
if n.nref is not None:
n.pref.nref = n.nref
n.nref.pref = n.pref
else:
if n.item == x:
n.pref.nref = None
else:
print("Element not found")
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())
30
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())
31
Output:
5
10
50
None
5
10
50
29
39
None
5
10
50
65
29
39
None
100
2929
39
None
10
50
None
Element not found
10
50
100
29
None
Result:
32
Ex.No:4c Implementation of Circular Singly Linked List
Date:
Aim:
Algorithm:
1. Defining the Node class which actually holds the data as well as 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
i. Checking whether or not the Linked List is empty
j. Adding a Node to the beginning of the Linked List
k. Adding a Node to the end of the Linked List
l. 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
33
Program:
class Node:
def init (self, data):
self.data = data
self.next = None
class CircularLinkedList:
def init (self):
self.head = None
def get_node(self, index):
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
def get_prev_node(self, ref_node):
if self.head is None:
return None
current = self.head
while current.next != ref_node:
current = current.next
return current
def insert_after(self, ref_node, new_node):
new_node.next = ref_node.next
34
ref_node.next = new_node
def insert_before(self, ref_node, new_node):
prev_node = self.get_prev_node(ref_node)
self.insert_after(prev_node, new_node)
def insert_at_end(self, new_node):
if self.head is None:
self.head = new_node
new_node.next = new_node
else:
self.insert_before(self.head, new_node)
def insert_at_beg(self, new_node):
self.insert_at_end(new_node)
self.head = new_node
def remove(self, 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:
print(current.data, end = ' ')
current = current.next
35
if current == self.head:
break
a_cllist = CircularLinkedList()
print('Menu')
print('insert <data> after <index>')
print('insert <data> before <index>')
print('insert <data> at beg')
print('insert <data> at end')
print('remove <index>')
print('quit')
while True:
print('The list will be: ', end = '')
a_cllist.display()
print()
do = input('What would you like to do? ').split()
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)
elif position == 'end':
a_cllist.insert_at_end(new_node)
else:
index = int(position)
36
ref_node = a_cllist.get_node(index)
if ref_node is None:
print('No such index.')
continue
if suboperation == 'after':
a_cllist.insert_after(ref_node, new_node)
elif suboperation == 'before':
a_cllist.insert_before(ref_node, new_node)
elif operation == 'remove':
index = int(do[1])
node = a_cllist.get_node(index)
if node is None:
print('No such index.')
continue
a_cllist.remove(node)
elif operation == 'quit':
break
37
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
Result:
38
Ex.No:4d Implementation of Circular Doubly Linked List
Date:
Aim:
Algorithm:
1. Defining the Node class which actually holds the data as well as 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 doubly
Linked List
m. Checking whether or not the Linked List is empty
n. Adding a Node to the beginning of the Linked List
o. Adding a Node to the end of the Linked List
p. Adding a Node in the middle of the Linked List
5. Defining the delete() method which is used to delete elements from the circular doubly
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 doubly Linked
List in a user-comprehendible form
39
Program:
class Node:
def init (self, data):
self.data = data
self.next = None
self.prev = None
class CircularDoublyLinkedList:
def init (self):
self.first = None
def get_node(self, index):
current = self.first
for i in range(index):
current = current.next
if current == self.first:
return None
return current
def insert_after(self, ref_node, new_node):
new_node.prev = ref_node
new_node.next = ref_node.next
new_node.next.prev = new_node
ref_node.next = new_node
def insert_before(self, ref_node, new_node):
self.insert_after(ref_node.prev, new_node)
def insert_at_end(self, new_node):
if self.first is None:
self.first = new_node
40
new_node.next = new_node
new_node.prev = new_node
else:
self.insert_after(self.first.prev, new_node)
def insert_at_beg(self, new_node):
self.insert_at_end(new_node)
self.first = new_node
def remove(self, 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:
print(current.data, end = ' ')
current = current.next
if current == self.first:
break
a_cdllist = CircularDoublyLinkedList()
print('Menu')
print('insert <data> after <index>')
print('insert <data> before <index>')
41
print('insert <data> at beg')
print('insert <data> at end')
print('remove <index>')
print('quit')
while True:
print('The list: ', end = '')
a_cdllist.display()
print()
do = input('What would you like to do? ').split()
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)
elif position == 'end':
a_cdllist.insert_at_end(new_node)
else:
index = int(position)
ref_node = a_cdllist.get_node(index)
if ref_node is None:
print('No such index.')
continue
if suboperation == 'after':
a_cdllist.insert_after(ref_node, new_node)
42
elif suboperation == 'before':
a_cdllist.insert_before(ref_node, new_node)
elif operation == 'remove':
index = int(do[1])
node = a_cdllist.get_node(index)
if node is None:
print('No such index.')
continue
a_cdllist.remove(node)
elif operation == 'quit':
break
43
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? remove 2
The list: 0 1 3 4
What would you like to do? quit
Result:
44
Ex.No:5a Implementation of Stack Using Linked List
Date:
Aim:
Algorithm:
2. Allocate memory to create a newNode with given value and name it as NEW_NODE.
4. If TOP == NULL means empty, then set newNode → next = NULL and TOP =
NEW_NODE.
5. If TOP != NULL, then set newNode → next = top and TOP = NEW_NODE.
45
Program:
class Node:
def init (self, data=None, next=None):
self.data = data
self.next = next
class Stack:
def init (self):
self.top = None
self.size=0
def push(self, data):
if self.top is None:
self.top = Node(data, None)
self.size += 1
return
self.top = Node(data, self.top)
self.size += 1
def pop(self):
if self.top is None:
return
temp = self.top
if self.top is not None:
self.top = self.top.next
temp.next = None
self.size -= 1
return temp.data
def getSize(self):
return self.size
def peek(self):
46
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
sstr = ' '
while itr:
sstr += str(itr.data) + '-->'
itr = itr.next
print(sstr)
if name == " main ":
stack = Stack()
stack.push(10)
stack.push(20)
stack.push(30)
stack.push(40)
print("List of elements in stack:")
stack.display()
print("The size of the stack is:",stack.getSize())
print("The top of the element is:",stack.peek())
print("The popped element from the stack:" ,stack.pop())
print("The size of the stack is:",stack.getSize())
stack.display()
print(stack.emptystack())
47
stack.clearstack()
print(stack.emptystack())
48
Output:
Result:
49
Ex.No:5b Implementation of Queue Using Linked List
Date:
Aim:
Algorithm:
3. Define two Node pointers 'front' and 'rear' and set both to NULL.
4. Create a newNode with given value and set 'newNode → next' to NULL.
7. If it is Not Empty then, set rear → next = newNode and rear = newNode
9. If it is Empty, then display "Queue is Empty!!! Deletion is not possible!!!" and terminate from the
function
10. If it is Not Empty then, define a Node pointer 'temp' and set it to 'front'.
11. Then set 'front = front → next' and delete 'temp' (free(temp)).
13. If it is Empty then, display 'Queue is Empty!!!' and terminate the function.
14. If it is Not Empty then, define a Node pointer 'temp' and initialize with front.
15. Display 'temp → data --->' and move it to the next node. Repeat the same until 'temp' reaches to 'rear'
(temp → next != NULL).
50
Program:
class Node:
def init (self, data, left=None, right=None):
self.data = data
self.next = None
class Queue:
def init (self):
self.rear = None
self.front = None
self.count = 0
def dequeue(self):
if self.front is None:
print('Queue Underflow')
exit(-1)
temp = self.front
print('Removing…', temp.data)
self.front = self.front.next
if self.front is None:
self.rear = None
self.count -= 1
return temp.data
51
def enqueue(self, item):
node = Node(item)
print('Inserting…', item)
if self.front is None:
self.front = node
self.rear = node
else:
self.rear.next = node
self.rear = node
self.count += 1
def peek(self):
if self.front:
return self.front.data
else:
exit(-1)
def isEmpty(self):
return self.rear is None and self.front is None
def size(self):
return self.count
if name == ' main ':
q = Queue()
q.enqueue(1)
q.enqueue(2)
q.enqueue(3)
q.enqueue(4)
print('The front element is', q.peek())
q.dequeue()
q.dequeue()
52
q.dequeue()
#q.dequeue()
if q.isEmpty():
print('The queue is empty')
else:
print('The queue is not empty')
print("The size of the queue is" ,q.size())
53
Output:
Result:
54
Ex.No:6a Implementation of Polynomial Manipulation Using List
Date:
Aim:
Algorithm:
4. Create a newNode with given value and insert the node, when the list is empty
5. If the list in not empty, compare the new node with the existing node
If the power value of newnode is greater than existing node, then insert the node as head element
Else, if the power value of newnode is smaller than existing node, then insert the node as next
element
If the power value of newnode is equal to existing node, then add the power value of existing node and
new node, insert the node
7. Define a two variable first and second and make the first = self.head , second = other.head
8. Check the power value of two variables, if it is equal, then add the power value and coefficient, then
insert the newnode in equation
10. Create the display method to print the values of both equation
55
Program:
class Node :
def init (self, data, power) :
self.data = data
self.power = power
self.next = None
def updateRecord(self, data, power) :
self.data = data
self.power = power
class AddPolynomial :
def init (self) :
self.head = None
def display(self) :
if (self.head == None) :
print("Empty Polynomial ")
print(" ", end = "")
temp = self.head
location.next = nodedef
addTwoPolynomials(self, other) :
result = None
tail = None
node = None
first = self.head
56
second = other.head
while (first != None or second != None) :
node = Node(0, 0)
if (result == None) :
result = node
if (first != None and second != None) :
if (first.power == second.power) :
node.updateRecord(first.data + second.data, first.power)
first = first.next
second = second.next
elif (first.power > second.power) :
node.updateRecord(first.data, first.power)
first = first.next
else :
node.updateRecord(second.data, second.power)
second = second.next
elif (first != None) :
node.updateRecord(first.data, first.power)
first = first.next
else :
node.updateRecord(second.data, second.power)
second = second.next
57
if (tail == None) :
tail = node
else :
tail.next = node
tail = node
return result
def main() :
poly1 = AddPolynomial()
poly2 = AddPolynomial()
result = AddPolynomial()
poly1.addNode(9, 3)
poly1.addNode(4, 2)
poly1.addNode(3, 0)
poly1.addNode(7, 1)
poly1.addNode(3, 4)
poly2.addNode(7, 3)
poly2.addNode(4, 0)
poly2.addNode(6, 1)
poly2.addNode(1, 2)
print("Polynomial A")
poly1.display()
print(" Polynomial B")
poly2.display()
result.head = poly1.addTwoPolynomials(poly2)
print(" Result")
result.display()
if name == " main ": main()
58
Output
Result:
59
Ex.No:6b Implementation of Infix to Postfix Conversion Using Stack
Date:
Aim:
To write a python program to implement infix to postfix using stack
Algorithm
Step 1 : Scan the Infix Expression from left to right.
Step 2 : If the scanned character is an operand, append it with final Infix to Postfix string.
Step 3 : Else,
Step 3.1 : If the precedence order of the scanned(incoming) operator is greater than
the precedence order of the operator in the stack (or the stack is empty or the stack contains
a ‘(‘ or ‘[‘ or ‘{‘), push it on stack.
Step 3.2 : Else, Pop all the operators from the stack which are greater than or equal
to in precedence than that of the scanned operator. After doing that Push the scanned
operator to the stack. (If you encounter parenthesis while popping then stop there and push
the scanned operator in the stack.)
Step 4 : If the scanned character is an ‘(‘ or ‘[‘ or ‘{‘, push it to the stack.
Step 5 : If the scanned character is an ‘)’or ‘]’ or ‘}’, pop the stack and and output it until a
‘(‘ or ‘[‘ or ‘{‘ respectively is encountered, and discard both the parenthesis.
Step 6 : Repeat steps 2-6 until infix expression is scanned.
Step 7 : Print the output
Step 8 : Pop and output from the stack until it is not empty.
60
Program:
class infix_to_postfix:
precedence={'^':5,'*':4,'/':4,'+':3,'-':3,'(':2,')':1}
def init (self):
self.items=[]
self.size=-1
def push(self,value):
self.items.append(value)
self.size+=1
def pop(self):
if self.isempty():
return 0
else:
self.size-=1
return self.items.pop()
def isempty(self):
if(self.size==-1):
return True
else:
return False
def seek(self):
if self.isempty():
return false
else:
return self.items[self.size]
def isOperand(self,i):
if i in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ':
61
return True
else:
return False
def infixtopostfix (self,expr):
postfix=""
print('postfix expression after every iteration is:')
for i in expr:
if(len(expr)%2==0):
print("Incorrect infix expr")
return False
elif(self.isOperand(i)):
postfix +=i
elif(i in '+-*/^'):
while(len(self.items)and self.precedence[i]<=self.precedence[self.seek()]):
postfix+=self.pop()
self.push(i)
elif i is '(':
self.push(i)
elif i is ')':
o=self.pop()
while o!='(':
postfix +=o
o=self.pop()
print(postfix)
#end of for
while len(self.items):
if(self.seek()=='('):
self.pop()
62
else:
postfix+=self.pop()
return postfix
s=infix_to_postfix()
expr=input('enter the expression ')
result=s.infixtopostfix(expr)
if (result!=False):
print("the postfix expr of :",expr,"is",result)
63
Output:
Result
64
Ex.No:6c Implementation of Queue Using Stack
Date:
Aim:
Algorithm:
2. Define a 'Node' structure with two members inbox and outbox. These two
members are used to call tha class Stack
3. Create the list item[] and insert the insert elements by using stack on queue
65
Program:
class Queue:
def init (self):
self.inbox = Stack()
self.outbox = Stack()
def is_empty(self):
return (self.inbox.is_empty() and self.outbox.is_empty())
def enqueue(self, data):
self.inbox.push(data)
def dequeue(self):
if self.outbox.is_empty():
while not self.inbox.is_empty():
popped = self.inbox.pop()
self.outbox.push(popped)
return self.outbox.pop()
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()
a_queue = Queue()
while True:
66
print('enqueue <value>')
print('dequeue')
print('quit')
do = input('What would you like to do? ').split()
operation = do[0].strip().lower()
if operation == 'enqueue':
a_queue.enqueue(int(do[1]))
elif operation == 'dequeue':
if a_queue.is_empty():
print('Queue is empty.')
else:
dequeued = a_queue.dequeue()
print('Dequeued element: ', int(dequeued))
elif operation == 'quit':
break
67
Output:
Result:
68
Ex.No:7a Implementation of Bubble Sort Algorithm
Date:
Aim:
Algorithm
69
Program
def bubbleSort(arr):
n = len(arr)
for i in range(n-1):
arr = list()
for i in range(n):
bubbleSort(arr)
70
Output:
Result:
71
Ex.No:7b Implementation of Selection Sort Algorithm
Date:
Aim:
Algorithm:
72
Program:
arr = list()
n=int(input("Enter the Size of the List:"))
for i in range(n):
arr.append(int(input("Enter the element:")))
print ("The array is:",arr)
for i in range(0,n):
j=i+1
for j in range(j, n):
if arr[i] > arr[j]:
arr[i] ,arr[j] =arr[j] ,arr[i]
print ("Sorted array is:",arr)
73
Output:
Result
74
Ex.No:7c Implementation of Insertion Sort Algorithm
Date:
Aim:
Algorithm
75
Program:
def insertionSort(arr):
for i in range(1, len(arr)):
key = arr[i]
j=i
j = i-1
while j >=0 and key < arr[j] :
arr[j+1] = arr[j]
j -= 1
arr[j+1] = key
print(arr)
arr = list()
n=int(input("Enter the Size of the List:"))
for i in range(n):
76
Output:
Result:
77
Ex.No:7d Implementation of Quick Sort Algorithm
Date:
Aim:
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.
78
Program:
import random
def pivot_place(list1,first,last):
rindex = random.randint(first, last)
list1[rindex], list1[last] = list1[last], list1[rindex]
pivot = list1[last]
left = first
right = last-1
while True:
while left <= right and list1[left] <= pivot:
left = left+1
while left <= right and list1[right] >= pivot:
right = right-1
if right < left:
break
else:
list1[left], list1[right] = list1[right], list1[left]
list1[last], list1[left] = list1[left], list1[last]
return left
def quicksort(list1, first, last):
if first < last:
p=pivot_place(list1, first, last)
quicksort(list1, first, p-1)
quicksort(list1, p+1, last)
list1 = list()
n=int(input("Enter the Size of the List:"))
for i in range(n):
list1.append(int(input("Enter the element:")))
79
print ("The array is:",list1)
quicksort(list1, 0, n-1)
print(list1)
80
Output:
Result:
81
Ex.No:7e Implementation of Merge Sort Algorithm
Date:
Aim:
Algorithm:
82
Program:
def mergeSort(arr):
if len(arr) > 1:
mid = len(arr)//2
L = arr[:mid]
R = arr[mid:]
mergeSort(L)
mergeSort(R)
i=0
j=0
k=0
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
while i < len(L):
arr[k] = L[i]
83
i += 1
k += 1
while j < len(R):
arr[k] = R[j]
j += 1
k += 1
def printList(arr):
for i in range(len(arr)):
print(arr[i], end=" ")
print()
arr = list()
n=int(input("Enter the Size of the List:"))
for i in range(n):
arr.append(int(input("Enter the element:")))
print ("The array is:",arr)
mergeSort(arr)
print("Sorted array is: ", end="\n")
printList(arr)
84
Output:
Enter the Size of the List:7
Enter the element:54
Enter the element:5
Enter the element:41
Enter the element:12
Enter the element:17
Enter the element:65
Enter the element:7
The array is: [54, 5, 41, 12, 17, 65, 7]
Sorted array is:
5 7 12 17 41 54 65
Result
85
Ex.No:7f Implementation of Linear Search Algorithm
Date:
Aim:
Algorithm:
86
Program:
else:
print ("element exist in position %d" %result)
87
Output:
Enter the Size of the List:5
Enter the element:45
Enter the element:12
Enter the element:78
Enter the element:65
Enter the element:48
The array is: [45, 12, 78, 65, 48]
Enter the element to be search:12
element exist in position 1
Result:
88
Ex.No:7g Implementation of Binary Search Algorithm
Date:
Aim:
Algorithm:
89
Program:
def binary_search(arr, low, high, x):
if arr[mid] == x:
return mid
else:
else:
return -1
arr = list()
for i in range(n):
if result != -1:
else:
90
Output:
Result
91
Ex.No:8a Implementation of Hashing with linear probing
Date:
Aim:
Algorithm:
92
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
93
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
94
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):
95
print("The number of element is the Table are : " + str(self.elementCount))
table1 = hashTable()
table1.insert(50)
table1.insert(100)
table1.insert(76)
table1.insert(85)
table1.insert(92)
table1.insert(73)
table1.insert(101)
table1.display()
print()
print()
table1.remove(73)
table1.display()
96
Output
Element 50 at position 1
Element 76 at position 6
Collision has occured for element 101 at position 3 finding new Position.
0 = 101
1 = 50
2 = 100
3 = 85
4 = 92
5 = 73
6 = 76
Element 73 is Deleted
0 = 101
1 = 50
2 = 100
3 = 85
4 = 92
97
5=0
6 = 76
Result:
98
Ex.No:8b Implementation of Hashing with Quadratic Probing
Date:
Aim:
Algorithm:
99
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
100
return posFound, newPosition
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
101
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")
102
for i in range(self.size):
table1 = hashTable()
table1.insert(50)
table1.insert(100)
table1.insert(76)
table1.insert(85)
table1.insert(92)
table1.insert(73)
table1.insert(101)
table1.display()
print()
print()
#table1.remove(90)
table1.remove(73)
table1.display()
103
Output:
Element 50 at position 1
Element 76 at position 6
Collision has occured for element 101 at position 3 finding new Position.
0 = 101
1 = 50
2 = 100
3 = 92
4 = 73
5 = 85
6 = 76
Element 73 is Deleted
0 = 101
1 = 50
2 = 100
3 = 92
104
4=0
5 = 85
6 = 76
Result:
105
Ex.No:8c Implementation of Hashing with double hashing
Date:
Aim:
Algorithm:
106
Program:
class doubleHashTable:
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
107
def insert(self, element):
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
108
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
109
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()
110
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
The position of element 9 is : 4
The position of element 58 is : 3
Total number of comaprisons done for searching = 4
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:
111
Ex.No:9 Implementation Of Tree Representation And Traversal Algorithm
Date:
Aim:
Algorithm:
112
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
113
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)
114
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))
115
Output
Result
116
Ex.No:10a Implementation Of Binary Search Tree
Date:
Aim:
Algorithm:
1. Insert node into the tree as the root of the tree.
2. Read the next element, if it is lesser than the root node element, insert it as the root of
the left sub-tree.
3. Otherwise, insert it as the root of the right of the right sub-tree
4. Compare the element with the root of the tree.
5. If the item is matched then return the location of the node.
6. Otherwise check if item is less than the element present on root, if so then move to
the left sub-tree.
7. If not, then move to the right sub-tree.
8. Repeat this procedure recursively until match found.
9. If element is not found then return NULL.
10. Find the data of the node to be deleted.
11. If the node is a leaf node, delete the node directly.
12. Else if the node has one child, copy the child to the node to be deleted and delete the
child node.
13. Else if the node has two children, find the inorder successor of the node.
14. Copy the contents of the inorder successor to the node to be deleted and delete the
inorder successor.
117
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
118
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)
119
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)
120
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->
Result:
121
Ex.No:10b Implementation Of AVL Tree
Date:
Aim:
Algorithm:
122
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:
123
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
124
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
125
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:
126
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()
127
root = None
nums = [15,20,24,10,13,7,30,36,25]
key = 24
key = 20
key = 15
128
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:
129
Ex.No:11a Implementation Of Max heap
Date:
Aim:
Algorithm:
12. Stop
130
Program:
def heapify(arr, n, i):
largest = i
l=2*i+1
r=2*i+2
if l < n and arr[i] < arr[l]:
largest = l
if r < n and arr[largest] < arr[r]:
largest = r
if largest != i:
arr[i],arr[largest] = arr[largest],arr[i]
heapify(arr, n, largest)
def insert(array, newNum):
size = len(array)
if size == 0:
array.append(newNum)
else:
array.append(newNum);
for i in range((size//2)-1, -1, -1):
heapify(array, size, i)
def deleteNode(array, num):
size = len(array)
i=0
for i in range(0, size):
if num == array[i]:
break
array[i], array[size-1] = array[size-1], array[i]
131
array.remove(num)
for i in range((len(array)//2)-1, -1, -1):
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)
print ("Max-Heap array: " + str(arr))
deleteNode(arr, 44)
print("After deleting an element: " + str(arr))
deleteNode(arr, 33)
print("After deleting an element: " + str(arr))
132
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]
Result:
133
Ex.No:11b Implementation Of Min heap
Date:
Aim:
Algorithm
134
Program:
def min_heapify(A,k):
l = left(k)
r = right(k)
if l < len(A) and A[l] < A[k]:
smallest = l
else:
smallest = k
if r < len(A) and A[r] < A[smallest]:
smallest = r
if smallest != k:
A[k], A[smallest] = A[smallest], A[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)
for k in range(n, -1, -1):
min_heapify(A,k)
A = [3,9,2,1,4,5] ,build_min_heap(A) , print(A)
135
Output:
Min heap:
[1, 3, 2, 9, 4, 5]
Result:
136
Ex.No:12a Implementation Of Graph Representation Using Adjacency List
Date:
Aim:
To write a program to implement graph representation using Adjacency list
Algorithm:
137
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
138
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()
139
Output
Result:
140
Ex.No:12b Implementation Of Graph Representation Using Adjacency Matrix
Date:
Aim:
To write a program to implement graph representation using Adjacency matrix
Algorithm:
141
Program:
class Graph:
n=0
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;
142
for i in range(0, self. n):
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();
143
Output
Adjacency Matrix:
0110
1010
1101
0010
Adjacency Matrix:
0110
1010
1101
0010
Adjacency Matrix:
010
101
010
Result:
144
Ex.No:12c Implementation Of Graph Traversal Algorithm Using BFS
Date:
Aim:
To write a program to implement graph traversal algorithm using BFS
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.
145
Program
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')
146
Output:
['A', 'B', 'C', 'E', 'D', 'F', 'G']
Result:
147
Ex.No:12d Implementation Of Graph Traversal Algorithm Using DFS
Date:
Aim:
To write a program to implement graph traversal algorithm using DFS
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.
148
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))
149
Output:
DFS
ABEICFJGDH
Result:
150
Ex.No:13 Implementation Of 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
151
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'))
152
Output:
shortest path
{'v1': 0, 'v2': 2, 'v3': 3, 'v4': 1, 'v5': 3, 'v6': 6, 'v7': 5}
Result:
153
Ex.No:14a Implementation Of Minimum spanning tree algorithm Using Kruskal’s
algorithm
Date:
Aim:
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.
154
Program:
class Edge :
def init (self, arg_src, arg_dst, arg_weight) :
self.src = arg_src
self.dst = arg_dst
self.weight = arg_weight
class Graph :
def init (self, arg_num_nodes, arg_edgelist) :
self.num_nodes = arg_num_nodes
self.edgelist = arg_edgelist
self.parent = []
self.rank = []
self.mst = []
def FindParent (self, node) :.
if node != self.parent[node] :
self.parent[node] = self.FindParent(self.parent[node])
return self.parent[node]
def KruskalMST (self) :
self.edgelist.sort(key = lambda Edge : Edge.weight)
self.parent = [None] * self.num_nodes
self.rank = [None] * self.num_nodes
for n in range(self.num_nodes) :
self.parent[n] = n
self.rank[n] = 0
for edge in self.edgelist :
root1 = self.FindParent(edge.src)
root2 = self.FindParent(edge.dst)
if root1 != root2 :
self.mst.append(edge)
if self.rank[root1] < self.rank[root2] :
self.parent[root1] = root2
self.rank[root2] += 1
else :
155
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()
156
Output:
Result
157
Ex.No:14b Implementation Of Minimum spanning tree algorithm Using Prim’s
algorithm
Date:
Aim:
Algorithm:
158
Program:
INF = 9999999
V=7
G = [[0, 2, 4, 1, 0, 0, 0],
[2, 0, 0, 3, 7, 0, 0],
[4, 0, 0, 2, 0, 5, 0],
[1, 3, 2, 0, 7, 8, 4],
[0, 7, 0, 7, 0, 0, 6],
[0, 0, 5, 8, 0, 0, 1],
[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
159
Output:
Edge : Weight
0-3:1
0-1:2
3-2:2
3-6:4
6-5:1
6-4:6
Result:
160