New Data Structures Design Lab Manual
New Data Structures Design Lab Manual
LABORATORY RECORD
REGISTER NO :
YEAR /SEMESTER :
DEPARTMENT:
Mr/Ms._____________________________________________________________________ for
TABLE OF CONTENTS
Sl. Page
Date Name of the Experiment Sign
No No
1 Implement simple ADTs as Python class
i
Downloaded by Anitha A ([email protected])
lOMoARcPSD|50370378
Ex. No: 01
Implement Simple ADT’s as Python
Date: Class
AIM:
To write a Python program to perform simple ADT’s.
ALGORITHM:
STEP 1: Start the program
STEP 2: Create array and read the values.
STEP 3: Print the result.
STEP 4: Create the list x1 and x2.
STEP 5: Read the values.
STEP 6: Print the result.
STEP 7: Assign new value for x2[1].
STEP 8: Print the result.
STEP 9: Create stack.
STEP 10: Perform insert and delete operation using append and pop method.
STEP 11: Display the result.
STEP 12: Create queue.
STEP 13: Perform insert and delete operation using append and pop method.
STEP 14: Display the result.
STEP 15: Create graph.
STEP 16: Use looing statement to compute vertices and edges and Perform insert operation
using append method.
STEP 17: Display the result.
STEP 18: Stop the program.
PROGRAM:
1.1 ARRAY ADT
import array as arr
a = arr.array("I",[3,6,9])
type(a)
print(a)
OUTPUT:
array('I', [3, 6, 9])
OUTPUT:
[1, 2, 3]
Apple
[1, 'orange', 3]
OUTPUT:
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4]
1.4 QUEUE ADT
queue = [1,2,3,4,5]
queue.append(6)
print(queue)
queue.pop(0)
queue.pop(0)
print(queue)
OUTPUT:
[1, 2, 3, 4, 5, 6]
[3, 4, 5, 6]
RESULT:
The python program to create simple ADT’s was successfully executed.
Ex. No: 02
Implement recursive algorithms in Python
Date:
AIM:
To write a Python program to perform recursive function.
ALGORITHM:
STEP 1: Start the program
STEP 2: Read the value of num.
STEP 3: Check IF x==1 means return 1.
STEP 4: Otherwise use recursive function (x * factorial(x-1)).
STEP 5: Print the result.
STEP 6: Stop the program.
PROGRAM:
def factorial(x):
if x == 1:
return 1
else:
return (x * factorial(x-1))
num = 3
print("The factorial of", num, "is", factorial(num))
OUTPUT:
The factorial of 3 is 6
RESULT:
The python program to find factorial of a number using recursive function was successfully
executed.
Ex. No: 03
Implement List ADT using Python arrays
Date:
AIM:
To write a Python program for List ADT’s using array.
ALGORITHM:
STEP 1: Start the program
STEP 2: Create a class.
STEP 3: Create an empty array inside the init function.
STEP 4: Create an object for that class
STEP 5: Do various list operation like insert, delete, append etc.
STEP 6: Print the result.
STEP 7: Stop the program.
PROGRAM:
class List:
def __init__self():
self.elements = []
self.slices = []
def delete(self):
return self.elements.pop()
definsertpos(self,pos,num):
size=(len(self.elements))
print (size)
if(pos<0):
print("invalid pos")
self.elements.insert(pos,num)
print(self.elements)
def deletepos(self,posdel):
return self.elements.pop(posdel)
def slice(self,start,end):
slices=self.elements[start:end]
5
print(slices)
def last(self):
return self.elements[-1]
def first(self):
return self.elements[0]
def is_empty(self):
return len(self.elements) == 0
list = List()
#adding the elements
list.insert(1)
list.insert(2)
list.insert(3)
list.insert(4)
list.insert(5)
print ("The elements in the list:",list.elements)
print("The first elements in the list:",list.first())
print("The last in the list:",list.last())
print("Check whether the list is empty or not:",list.is_empty())
#removing the element -> 1
pos=int(input("enter the position to insert an element"))
num=int(input("enter a number"))
list.insertpos(pos,num)
list.delete()
print ("The elements in the list after delete:",list.elements)
posdel=int(input("enter the position to delete"))
list.deletepos(posdel)
print ("The elements in the list:",list.elements)
start=int(input("enter the starting index value"))
end=int(input("enter the end index value"))
list.slice(start,end)
OUTPUT:
The elements in the list: [1, 2, 3, 4, 5]
The first elements in the list: 1
The last in the list: 5
Check whether the list is empty or not: False
enter the position to insert an element 3
enter a number 7
[1, 2, 3, 7, 4, 5]
The elements in the list after delete: [1, 2, 3, 7, 4]
RESULT:
The python program for creating list was successfully executed.
Ex. No: 04
Linked list implementations of List
Date:
AIM:
To write a Python program for Linked list implementation of list.
ALGORITHM:
STEP 1: Start the program
STEP 2: Create a class.
STEP 3: Create a node with contain both data and next field.
STEP 4: Do various linked list operation like insert, delete and display.
STEP 6: Print the result.
STEP 7: Stop the program.
PROGRAM:
4.1 INSERTION
class Node:
def __init__(self, dataval=None):
self.dataval = datival
self.nextval = None
class SLinkedList:
def _ _ init__(self):
self.headval = None
laste = laste.nextval
laste.nextval=NewNode
list = SLinkedList()
list.headval = Node("Mon")
e2 = Node("Tue")
e3 = Node("Thu")
list.headval.nextval = e2
e2.nextval = e3
list.AtBegining("Sun")
list.Inbetween(list.headval.nextval,"Fri")
list.AtEnd("Thu")
list.listprint()
OUTPUT
Sun
Mon
Fri
Tue
Thu
Thu
9
4.2 DELETE
class Node:
def _ _ init__ (self, data=None):
self.data = data
self.next = None
class SLinkedList:
def __init__ (self):
self.head = None
def LListprint(self):
printval = self.head
while (printval):
print(printval.data)
printval = printval.next
llist = SLinkedList()
llist.Atbegining("Mon")
llist.Atbegining("Tue")
llist.Atbegining("Wed")
llist.Atbegining("Thu")
llist.RemoveNode("Tue")
llist.LListprint()
10
OUTPUT:
Thu
Wed
Mon
RESULT:
The python program for creating linked list was successfully executed.
11
Ex. No: 5A
Implementation of Stack ADT’S using List
Date:
AIM:
To write a Python program for stack implementation using list.
ALGORITHM:
PROGRAM:
class Stack:
def _ _ init__ (self):
self.elements = []
def pop(self):
return self.elements.pop()
def peek(self):
return self.elements[-1]
def is_empty(self):
return len(self.elements) == 0
stack = Stack()
## checking is_empty method -> true
print("Whether the stack is empty-->",stack.is_empty())
#pushing the elements
stack.push(1)
stack.push(2)
stack.push(3)
stack.push(4)
stack.push(5)
print("The elements in the stack is:",stack.elements)
#again checking is_empty method -> false
print("Whether the stack is empty-->",stack.is_empty())
12
OUTPUT:
Whether the stack is empty--> True
The elements in the stack is: [1, 2, 3, 4,
5] Whether the stack is empty--> False
The topmost element in the stack: 5 pop 5
RESULT:
The python program for creating a stack ADT was successfully executed.
13
Ex. No: 5B
Implementation of Queue ADT’S using List
Date:
AIM:
To write a Python program for Queue implementation using list.
ALGORITHM:
STEP 1: Start the program
STEP 2: Create a class.
STEP 3: Do various queue operation like insert, delete and display.
STEP 4: Print the result.
STEP 5: Stop the program.
PROGRAM:
class Queue:
def _ _ init__ (self):
self.elements = []
def enqueue(self, data):
self.elements.append(data)
return data
def rear(self):
return self.elements[-1]
def front(self):
return self.elements[0]
def is_empty(self):
return len(self.elements) == 0
def dequeue(self):
return self.elements.pop(0)
queue = Queue()
#adding the elements
queue.enqueue(1)
queue.enqueue(2)
queue.enqueue(3)
queue.enqueue(4)
queue.enqueue(5)
print ("The elements in the
queue:",queue.elements) print("The elements in
the rear is:",queue.rear()) print("The elements in
the front is:",queue.front())
print("Check whether the queue is empty or not:",queue.is_empty())
#removing the element -> 1
queue.dequeue()
queue.dequeue()
print ("The elements in the queue:",queue.elements)
14
OUTPUT:
The elements in the queue: [1, 2, 3, 4, 5]
The elements in the rear is: 5
The elements in the front is: 1
Check whether the queue is empty or not:
False
RESULT:
The python program for creating a queue ADT was successfully executed.
15
AIM:
To write a Python program for Stack Application.
ALGORITHM:
STEP 1: Start the program
STEP 2: Create a class.
STEP 3: Do various operations.
STEP 4: Print the result.
STEP 5: Stop the program.
PROGRAM:
# set of operators
OPERATORS = set(['+', '-', '*', '/', '(', ')', '^'])
# dictionary having priorities
PRIORITY = {'+':1, '-':1, '*':2, '/':2, '^':3}
def infix_to_postfix(expression): #input expression
stack = [] # initially stack empty
output = ‘’ # initially output empty
for ch in expression:
if ch not in OPERATORS: # if an operand then put it directly in postfix expression
output+= ch
elif ch=='(': # else operators should be put in stack
stack.append('(')
elif ch==')':
while stack and stack[-1]!= '(':
output+=stack.pop()
stack.pop()
else:
# lesser priority can't be on top on higher or equal priority
# so pop and put in output
while stack and stack[-1]!='(' and PRIORITY[ch]<=PRIORITY[stack[-1]]:
output+=stack.pop()
stack.append(ch)
while stack:
output+=stack.pop()
return output
expression = input('Enter infix expression')
print('infix expression: ',expression)
16
OUTPUT:
Enter infix expressiona+b*c
infix expression: a+b*c
postfix expression: abc*+
RESULT:
The python program for creating a Stack application was successfully executed.
17
AIM:
To write a Python program for Queue application.
ALGORITHM:
STEP 1: Start the program
STEP 2: Create a class.
STEP 3: Do various operations.
STEP 4: Print the result.
STEP 5: Stop the program.
PROGRAM:
class Queue:
def __init__(self,max_size):
self.__max_size=max_size
self.__elements=[None]*self.__max_size
self.__rear=-1
self.__front=0
def is_full(self):
if(self.__rear==self. __max_size-1):
return True
return False
def is_empty(self):
if(self.__front>self.__rear):
return True
return False
def enqueue(self,data):
if(self.is_full()):
print("Queue is full!!!")
else:
self.__rear+=1
self.__elements[self.__rear]=data
def dequeue(self):
if(self.is_empty()):
print("Queue is empty!!!")
else:
data=self.__elements[self.__front]
self.__front+=1
return data
18
def display(self):
for index in range(self.__front, self.__rear+1):
print(self.__elements[index])
def get_max_size(self):
return self.__max_size
#You can use the below __str__() to print the elements of the DS object while
#debugging
def __str__(self):
msg=[]
index=self.__front
while(index<=self.__rear):
msg.append((str)(self.__elements[index]))
index+=1
msg=" ".join(msg)
msg="Queue data(Front to Rear): "+msg
return msg
#function that enqueue are the documents to be printed in Queue named print_queue
def send_for_print(doc):
global print_queue
if(print_queue.is_full()):
print("Queue is full")
else:
print_queue.enqueue(doc)
print(doc,"sent for printing")
#function that prints the document if number of pages of document is less than
#total number of pages in printer
def start_printing():
global print_queue
while(not print_queue.is_empty()):
#here we dequeue the Queue and take the coument that was input first for printing.
doc=print_queue.dequeue()
global pages_in_printer
#the aim of this for loop is to find number of pages of the of document which is doc
name #followed by “-“
for i in range(0,len(doc)):
if(doc[i]=="-"):
no_of_pages=int(doc[i+1:])
break
if(no_of_pages<=pages_in_printer):
print(doc,"printed")
pages_in_printer-=no_of_pages
print("Remaining no. of pages in printer:", pages_in_printer)
else:
print("Couldn't print",doc[:i],". Not enough pages in the printer.")
pages_in_printer=12
print_queue=Queue(10)
send_for_print("doc1-5")
19
send_for_print("doc2-3")
send_for_print("doc3-6")
start_printing()
OUTPUT:
doc1-5 sent for printing
doc2-3 sent for printing
doc3-6 sent for printing
doc1-5 printed
Remaining no. of pages in printer: 7
doc2-3 printed
Remaining no. of pages in printer: 4
Couldn't print doc3 . Not enough pages in the printer.
RESULT:
The python program for creating a Queue application was successfully executed.
20
AIM:
To write a Python program for List application.
ALGORITHM:
STEP 1: Start the program
STEP 2: Create a class.
STEP 3: Do various operations.
STEP 4: Print the result.
STEP 5: Stop the program.
PROGRAM:
class students:
count = 0
def init(self, name):
self.name = name
self.marks = []
students.count = students.count + 1
def enterMarks(self):
for i in range(3):
m = int(input("Enter the marks of %s in %d subject: "%(self.name, i+1)))
self.marks.append(m)
def display(self):
print(self.name, "got ", self.marks)
21
OUTPUT:
Enter the name of Student:RAMA
Enter the marks of RAMA in 1 subject: 60
Enter the marks of RAMA in 2 subject: 70
Enter the marks of RAMA in 3 subject: 80
RAMA got [60, 70, 80]
RESULT:
The python program for creating a List application was successfully executed.
22
Ex. No:7A
Implementation of sorting algorithms
Date:
AIM:
To write a Python program for various sorting algorithms.
ALGORITHM:
STEP 1: Start the program.
STEP 2: Bubble Sort:
Starting with the first element(index = 0), compare the current element with the next
element of the array.
If the current element is greater than the next element of the array, swap them.
If the current element is less than the next element, move to the next element
STEP 3: Insertion Sort:
If it is the first element, it is already sorted.
Pick the next element.
Compare with all the elements in sorted sub-list.
Shift all the elements in sorted sub-list that is greater than the value to be sorted.
Insert the value.
Repeat until list is sorted
STEP 4: Selection Sort:
Get a list of unsorted numbers
Set a marker for the unsorted section at the front of the list
Repeat STEPs 4 - 6 until one number remains in the unsorted section
Compare all unsorted numbers in order to select the smallest one
Swap this number with the first number in the unsorted section
Advance the marker to the right one position
STEP 5: Quick Sort:
Choose the highest index value has pivot
Take two variables to point left and right of the list excluding pivot left points to the low
index
23
PROGRAM:
7a.1. BUBBLE SORT
def b_sort(a):
n = len(a)
for i in range(n):
for j in range(0, n-i-1):
if a[j] > a[j+1] :
a[j], a[j+1] = a[j+1], a[j]
print("Enter elements into list:")
a=[int(x) for x in input().split()]
b_sort(a)
print("The sorted list is ",a)
OUTPUT:
24
OUTPUT:
def s_sort(a):
for i in range(len(a)):
least=i
for k in range(i+1,len(a)):
if a[k]<a[least]:
least=k swap(a,least,i)
def swap(a,least,i):
temp=a[least]
a[least]=a[i]
a[i]=temp
25
OUTPUT:
def partition(a,low,high):
pivotvalue=a[low]
up=low+1
down=high
done=False
while not done:
while up<=down and a[up]<=pivotvalue:
up+=1
while down>=up and a[down]>=pivotvalue:
down-=1
if down<up:
done=True
else:
26
temp=a[up]
a[up]=a[down]
a[down]=temp
temp=a[low]
a[low]=a[down]
a[down]=temp
return down
OUTPUT:
def m_sort(a):
for i in range(len(a)):
if i>1:
mid=len(a)//2
l_half=a[:mid]
r_half=a[mid:]
m_sort(l_half)
m_sort(r_half)
i=j=k=0
while i<len(l_half) and j<len(r_half):
if l_half[i]<r_half[j]:
27
a[k]=l_half[i] i+=1
else:
a[k]=r_half[j] j+=1
k+=1
while i<len(l_half):
a[k]=l_half[i]
i+=1
k+=1
while j<len(r_half):
a[k]=r_half[j]
j+=1
k+=1
OUTPUT:
RESULT:
The python program for creating a sorting algorithms was successfully execute.
28
Ex. No: 7B
Implementation of searching algorithms
Date:
AIM:
To write a Python program for various searching algorithms.
ALGORITHM:
PROGRAM:
7 b.1 LINEAR SEARCH:
def L_search(a,e,n):
for i in range(n):
if a[i] == e:
return i+1
return -1
print("\tLINEAR SEARCH")
print("\t*************")
print("Enter list:")
29
OUTPUT:
Linear Search
30
OUTPUT:
RESULT:
The python program for creating a Searching algorithms was successfully executed.
31
Ex. No:8
Implementation of Hash tables
Date:
AIM:
To write a Python program to implement hash table using dictionary.
ALGORITHM:
STEP 1: Start the program.
STEP 2: Creating the hash table as a nested list.
STEP 3: Insert Data into the Hash Table.
STEP 4: Search Data from the Hash Table.
STEP 5: Delete Data from the Hash Table.
STEP 6: Stop the Program.
PROGRAM:
#create
hash_table = [[] for _ in range(10)]
print (hash_table)
#insert
def insert(hash_table, key, value):
hash_key = hash(key) % len(hash_table)
key_exists = False
bucket = hash_table[hash_key]
for i, kv in enumerate(bucket):
k, v = kv
if key == k:
key_exists = True
break
if key_exists:
bucket[i] = ((key, value))
else:
bucket.append((key, value))
#search
def search(hash_table, key):
hash_key = hash(key) % len(hash_table)
bucket = hash_table[hash_key]
32
for i, kv in enumerate(bucket):
k, v = kv
if key == k:
return v
#delete
def delete(hash_table, key):
hash_key = hash(key) % len(hash_table)
key_exists = False
bucket = hash_table[hash_key]
for i, kv in enumerate(bucket):
k, v = kv
if key == k:
key_exists = True
break
if key_exists:
del bucket[i]
print ('Key {} deleted'.format(key))
else:
print ('Key {} not found'.format(key)
delete(hash_table, 100)
print (hash_table)
delete(hash_table, 10)
print (hash_table)
OUTPUT:
[[], [], [], [], [], [], [], [], [], []]
[[(10, 'Nepal'), (20, 'India')], [], [], [], [], [(25, 'USA')], [], [], [], []]
Nepal
India
None
Key 100 not found
[[(10, 'Nepal'), (20, 'India')], [], [], [], [], [(25, 'USA')], [], [], [], []]
Key 10 deleted
[[(20, 'India')], [], [], [], [], [(25, 'USA')], [], [], [], []]
RESULT:
The python program for hash table implementation was successfully executed.
33
AIM:
To write a Python program for tree representation and tree traversal algorithms.
ALGORITHM:
STEP 1: Start the program
STEP 2: Inorder(tree)
1. Traverse the left subtree.
2. Visit the root.
3. Traverse the right subtree.
STEP 3: Preorder(tree)
1. Visit the root.
2. Traverse the left subtree.
3. Traverse the right subtree.
STEP 4: Postorder(tree)
1. Traverse the left subtree, i.e., call Postorder(left-subtree)
2. Traverse the right subtree, i.e., call Postorder(right-subtree)
3. Visit the root.
PROGRAM:
9.1 INORDER:
class Node:
def __init__(self, data):
self.left = None
self.right = None
self.data = data
# Insert Node
def insert(self, data):
if self.data:
if data < self.data:
if self.left is None:
self.left = Node(data)
34
else:
self.left.insert(data)
elif data > self.data:
if self.right is None:
self.right = Node(data)
else:
self.right.insert(data)
else:
self.data = data
OUTPUT:
Inorder: [10, 14, 19, 27, 31, 35, 42]
35
9.2 PREORDER:
class Node:
# Insert Node
def insert(self, data):
if self.data:
if data < self.data:
if self.left is None:
self.left = Node(data)
else:
self.left.insert(data)
elif data > self.data:
if self.right is None:
self.right = Node(data)
else:
self.right.insert(data)
else:
self.data = data
# Print the Tree
def PrintTree(self):
if self.left:
self.left.PrintTree()
print( self.data)
if self.right:
self.right.PrintTree()
# Preorder traversal
# Root -> Left ->Right
def PreorderTraversal(self, root):
res = []
if root:
res.append(root.data)
res = res + self.PreorderTraversal(root.left)
res = res + self.PreorderTraversal(root.right)
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.PreorderTraversal(root))
OUTPUT:
36
37
9.3 POSTORDER:
class Node:
def __init__(self, data):
self.left = None
self.right = None
self.data = data
# Insert Node
def insert(self, data):
if self.data:
if data < self.data:
if self.left is None:
self.left = Node(data)
else:
self.left.insert(data)
elif data > self.data:
if self.right is None:
self.right = Node(data)
else:
self.right.insert(data)
else:
self.data = data
# Print the Tree
def PrintTree(self):
if self.left:
self.left.PrintTree()
print( self.data)
if self.right:
self.right.PrintTree()
# Postorder traversal
# Left ->Right -> Root
def PostorderTraversal(self, root):
res = []
if root:
res = self.PostorderTraversal(root.left)
res = res + self.PostorderTraversal(root.right)
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.PostorderTraversal(root))
38
OUTPUT:
Inorder: [10, 14, 19, 27, 31, 35, 42]
Preorder: [27, 14, 10, 19, 35, 31, 42]
Postorder: [10, 19, 14, 31, 42, 35, 27]
RESULT:
The python program for tree traversal was successfully executed.
39
AIM:
To write a Python program to implement binary search trees.
ALGORITHM:
STEP 1: Start the program.
STEP 2: Preorder Traversal:
Visit the root (we will print it when we visit to show the order of visiting)
Traverse the left subtree in pre-order
Traverse the right subtree in pre-order
STEP 3: In-order traversal:
PROGRAM:
class BSTNode:
def __init__(self, val=None):
self.left = None
self.right = None
self.val = val
40
def get_min(self):
current = self
while current.left is not None:
current = current.left
return current.val
def get_max(self):
current = self
while current.right is not None:
current = current.right
return current.val
return False
return self.left.exists(val)
if self.right == None:
return False
return self.right.exists(val)
print("4 exists:")
print(bst.exists(4))
print("6 exists:")
print(bst.exists(6))
print("12 exists:")
print(bst.exists(12))
print("18 exists:")
print(bst.exists(18))
OUTPUT:
preorder:
[12, 6, 3, 5, 4, 11, 18, 19, 21, 24]
#
postorder:
[4, 5, 3, 11, 6, 24, 21, 19, 18, 12]
#
inorder:
[3, 4, 5, 6, 11, 12, 18, 19, 21, 24]
#
deleting [2, 6, 20]
#
4 exists:
True
6 exists:
False
12 exists:
True
18 exists:
True
RESULT:
The python program for creating a Stack application was successfully executed.
43
Ex. No: 11
Implementation of Heaps
Date:
AIM:
To write a Python program for Heaps.
ALGORITHM:
STEP 1: Start the program.
STEP 2: Create a new child node at the end of the heap (last level).
PROGRAM:
"""
Min Heap Implementation in
Python
"""
class MinHeap:
def _ _ init __(self):
"""
On this implementation the heap list is initialized
with a value
"""
self.heap_list = [0]
self.current_size = 0
def delete_min(self):
# Equal to 1 since the heap list was initialized with a value
if len(self.heap_list) == 1:
return 'Empty heap'
# Get root of the heap (The min value of the
heap) root = self.heap_list[1]
# Move the last value of the heap to the root
self.heap_list[1] = self.heap_list[self.current_size]
# Pop the last value since a copy was set on the root
*self.heap_list, _ = self.heap_list
# Decrease the size of the heap
self.current_size -= 1
# Move down the root (value at index 1) to keep the heap property
self.sift_down(1)
# Return the min value of the
heap return root
45
OUTPUT:
5
RESULT:
The python program for creating a Heap was successfully executed.
46
AIM:
To write a Python program for Graph representation and Traversal algorithms.
ALGORITHM:
STEP 1: Start the program.
STEP 2: Take the graph as input and find the adjacency list.
STEP 3: Start at a random vertex and visit all nodes using depth first search (DFS) and
then breadth first search (BFS).
STEP 4: Use stack for DFS and queue for BFS.
STEP 5: Stop the program.
PROGRAM:
BREADTH FIRST SEARCH PROGRAM
from queue import Queue
def bfs(graph, start):
visited = []
queue = Queue()
queue.put(start)
while not queue.empty():
vertex = queue.get()
if vertex not in visited:
visited.append(vertex)
for vert in graph[vertex]:
if vert not in visited:
queue.put(vert)
return visited
47
OUTPUT:
VERTEX C
GRAPH[VERTEX]: {'F', 'A'}
GRAPH[VERTEX]-visited: {'A'}
STACK: ['A', 'A']
VERTEX A
GRAPH[VERTEX]: {'C', 'B'}
GRAPH[VERTEX]-visited: set()
STACK: ['A']
VERTEX A
{'F', 'D', 'A', 'B', 'E', 'C'}
RESULT:
The python program for BFS & DFS was successfully executed.
49
ALGORITHM:
STEP 1: Initialize the distance from the source node S to all other nodes as infinite and to
itself as 0.
STEP 2: Insert the pair of < node, distance > for source i.e < S, 0 > in a DICTIONARY
STEP 3: While the DICTIONARY is not empty do
STEP 4: current_source_node = DICTIONARY . get_key (node)_with_smallest_value (dist)
Remove the key (current_source_node) from the DICTIONARY.
STEP 5: For every adjacent_node to the current_source_node do
STEP 6: if(distance[ adjacent_node ] >
length_of_path_to_adjacent_node_from_current_source + distance [ current_source_node ] )
STEP 7: distance [ adjacent_node ] = length_of_path_to_adjacent_node_from_current_source
+ distance [ current_source_node ]
STEP 8: Update the DICTIONARY with the new pair < adjacent_node,
distance [ adjacent_node ] .
PROGRAM:
class Graph :
def __ init__ (self, node_count) :
# Store the adjacency list as a dictionary
# The default dictionary would create an empty list as a default (value)
# for the nonexistent keys.
self.adjlist = defaultdict(list)
self.node_count = node_count
50
def main() :
g = Graph(6)
# Node 0: <1,5> <2,1> <3,4>
g.Add_Into_Adjlist(0, Node_Distance(1, 5))
g.Add_Into_Adjlist(0, Node_Distance(2, 1))
g.Add_Into_Adjlist(0, Node_Distance(3, 4))
# Node 1: <0,5> <2,3> <4,8>
g.Add_Into_Adjlist(1, Node_Distance(0, 5))
g.Add_Into_Adjlist(1, Node_Distance(2, 3))
g.Add_Into_Adjlist(1, Node_Distance(4, 8))
# Node 2: <0,1> <1,3> <3,2> <4,1>
g.Add_Into_Adjlist(2, Node_Distance(0, 1))
g.Add_Into_Adjlist(2, Node_Distance(1, 3))
g.Add_Into_Adjlist(2, Node_Distance(3, 2))
g.Add_Into_Adjlist(2, Node_Distance(4, 1))
# Node 3: <0,4> <2,2> <4,2> <5,1>
g.Add_Into_Adjlist(3, Node_Distance(0, 4)
51
OUTPUT:
Source Node (0) -> Destination Node(0) : 0
Source Node (0) -> Destination Node(1) : 4
Source Node (0) -> Destination Node(2) : 1
Source Node (0) -> Destination Node(3) : 3
Source Node (0) -> Destination Node(4) : 2
RESULT:
The python program for single source shortest path algorithm was successfully executed.
52
AIM:
To write a Python program for minimum spanning tree algorithms.
ALGORITHM:
STEP 1: Create a dictionary (to be used as a priority queue) PQ to hold pairs of (node,
cost).
STEP 2: Push [S, 0] ( node, cost ) in the dictionary PQ (i.e) Cost of reaching vertex S
from
source node S is zero.
STEP 3: While PQ contains ( V, C ) pairs
STEP 4: Get the adjacent node V ( key ) with the smallest edge cost ( value ) from the
d ictionary PQ.
STEP 5: Cost C = PQ [V]
STEP 6: Delete the key-value pair (V, C) from the dictionary PQ.
STEP 7: If the adjacent node V is not added to the spanning tree. STEP 8. Add node V to
the spanning tree.
STEP 9: Cost of the spanning tree += Cost C
STEP 10: For all vertices adjacent to vertex V not added to spanning
tree. STEP 11: Push pair of (adjacent node, cost ) into the dictionary
PQ.
PROGRAM:
class Node :
def __init__(self, arg_id) :
self._id = arg_id
class Graph :
def __init__(self, arg_source, arg_adj_list) :
self.source = arg_source
self.adjlist = arg_adj_list
def PrimsMST(self):
# Priority queue is implemented as a dictionary with
# key as an object of 'Node' class and value as the cost of
# reaching the node from the source.
53
# Since the priority queue can have multiple entries for the
# same adjacent node but a different cost, we have to use objects as
# keys so that they can be stored in a dictionary.
# [As dictionary can't have duplicate keys so objectify the key]
# The distance of source node from itself is 0. Add source node as the first node
# in the priority queue
priority_queue = { Node(self.source) : 0 }
added = [False] * len(self.adjlist)
min_span_tree_cost = 0
while priority_queue :
# Choose the adjacent node with the least edge cost
node = min (priority_queue, key=priority_queue.get)
cost = priority_queue[node]
# Remove the node from the priority queue
del priority_queue[node]
if added[node._id] == False :
min_span_tree_cost += cost
added[node._id] = True
print("Added Node : " + str(node._id) + ", cost now : "+str(min_span_tree_cost))
for item in self.adjlist[node._id] :
adjnode = item[0]
adjcost = item[1]
if added[adjnode] == False :
priority_queue[Node(adjnode)] = adjcost
return min_span_tree_cost
g1_edges_from_node = {}
# Outgoing edges from the node: (adjacent_node, cost) in graph 1.
g1_edges_from_node[0] = [ (1,1), (2,2), (3,1), (4,1), (5,2), (6,1) ]
g1_edges_from_node[1] = [ (0,1), (2,2), (6,2) ]
g1_edges_from_node[2] = [ (0,2), (1,2), (3,1) ]
g1_edges_from_node[3] = [ (0,1), (2,1), (4,2) ]
g1_edges_from_node[4] = [ (0,1), (3,2), (5,2) ]
g1_edges_from_node[5] = [ (0,2), (4,2), (6,1) ]
g1_edges_from_node[6] = [ (0,1), (2,2), (5,1) ]
g1 = Graph(0, g1_edges_from_node) cost = g1.PrimsMST()
print("Cost of the minimum spanning tree in graph 1 : " + str(cost) +"\n")
# Outgoing edges from the node: (adjacent_node, cost) in graph 2.
g2_edges_from_node = {}
g2_edges_from_node[0] = [ (1,4), (2,1), (3,5) ]
g2_edges_from_node[1] = [ (0,4), (3,2), (4,3), (5,3) ]
g2_edges_from_node[2] = [ (0,1), (3,2), (4,8) ]
g2_edges_from_node[3] = [ (0,5), (1,2), (2,2), (4,1) ]
54
OUTPUT:
Added Node : 0, cost now : 0
Added Node : 1, cost now : 1
Added Node : 3, cost now : 2
Added Node : 4, cost now : 3
Added Node : 6, cost now : 4
Added Node : 2, cost now : 5
Added Node : 5, cost now : 6
Cost of the minimum spanning tree in graph 1 : 6
Added Node : 0, cost now : 0
Added Node : 2, cost now : 1
Added Node : 3, cost now : 3
Added Node : 4, cost now : 4
Added Node : 1, cost now : 6
Added Node : 5, cost now : 9
Cost of the minimum spanning tree in graph 2 : 9
RESULT:
The python program for minimum spanning tree algorithms was successfully executed.
55
Ex. No: 15
Implementation of AVL tree
Date:
AIM:
To write a Python program for AVL tree.
PROGRAM:
class node:
def __init __(self, num):
self.value = num
self.left = None
self.right = None
self.height = 1
class AVL:
def height(self, Node):
if Node is None:
return 0
else:
return Node.height
56
57
else:
if Node.left is None:
lt = Node.right
Node = None
return lt
elif Node.right is None:
lt = Node.left
Node = None
return lt
rgt = self.MinimumValueNode(Node.right)
Node.value = rgt.value
Node.right = self.delete(rgt.value, Node.right)
if Node is None:
return Node
Node.height = 1 + max(self.height(Node.left), self.height(Node.right))
balance = self.balance(Node)
if balance > 1 and self.balance(Node.left) >= 0:
return self.rotateR(Node)
if balance < -1 and self.balance(Node.right) <= 0:
return self.rotateL(Node)
if balance > 1 and self.balance(Node.left) < 0:
Node.left = self.rotateL(Node.left)
return self.rotateR(Node)
if balance < -1 and self.balance(Node.right) > 0:
Node.right = self.rotateR(Node.right)
return self.rotateL(Node)
return Node
Tree = AVL()
rt = None
rt = Tree.insert(3, rt)
rt = Tree.insert(5, rt)
rt = Tree.insert(7, rt)
print("PREORDER")
Tree.preorder(rt)
rt = Tree.insert(1, rt)
rt = Tree.insert(2, rt)
print("PREORDER")
Tree.preorder(rt)
rt = Tree.insert(4, rt)
rt = Tree.insert(6, rt)
rt = Tree.delete(7, rt)
rt = Tree.insert(8, rt)
rt = Tree.insert(9, rt)
58
print("PREORDER")
Tree.preorder(rt)
rt = Tree.delete(3, rt)
print("PREORDER")
Tree.preorder(rt)
OUTPUT:
PREORDER 5
3
PREORDER
PREORDER
3
2
PREORDER
4
2
9
59
RESULT:
The python program for implementing AVL Tree was successfully executed.
60