0% found this document useful (0 votes)
2 views76 pages

Laboratory Manual: Jaya Sakthi Engineering College

The document is a laboratory manual for a Data Structures and Algorithms course at Jaya Sakthi Engineering College, detailing various experiments to be conducted using Python. It includes implementations of Abstract Data Types (ADTs) such as stacks, queues, linked lists, and algorithms for sorting, searching, and tree traversal. Each experiment outlines the aim, algorithm, program code, output, and results of the implementation.

Uploaded by

sandhyamca31
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views76 pages

Laboratory Manual: Jaya Sakthi Engineering College

The document is a laboratory manual for a Data Structures and Algorithms course at Jaya Sakthi Engineering College, detailing various experiments to be conducted using Python. It includes implementations of Abstract Data Types (ADTs) such as stacks, queues, linked lists, and algorithms for sorting, searching, and tree traversal. Each experiment outlines the aim, algorithm, program code, output, and results of the implementation.

Uploaded by

sandhyamca31
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 76

JAYA SAKTHI ENGINEERING COLLEGE

Thiruninravur– 602 024, Thiruvallur Dt., Tamil Nadu.


(Approved by AICTE, New Delhi &Affiliated To
Anna
University, Chennai)

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

LABORATORY MANUAL

CD3281-DATA STRUCTURES AND ALGORTHIMS

LABORATORY

REGULATION – 2021

II YEAR / THIRD SEMESTER


LIST OF EXPERIMENTS

1. Implement simple ADTs as Python classes

2. Implement recursive algorithms in Python

3. Implement List ADT using Python arrays

4. Linked list implementations of List

5.Implementation of Stack and Queue ADTs

6.Applications of List, Stack and Queue ADTs

7.Implementation of sorting and searching

algorithms

8. Implementation of Hash tables

9. Tree representation and traversal

algorithms 10.Implementation of Binary

Search Trees 11.Implementation of Heaps

Lab Manual

12. Graph representation and Traversal algorithms

13. Implementation of single source shortest path algorithm

14. Implementation of minimum spanning tree algorithms


EX.NO:1
SIMPLE ADTS-PYTHON CLASSES
DATE:

AIM:
To implement stack and queue ADT as python classes.

ALGORITHM:

Step 1: Start
Step 2: Create a class stack, queue and instantiate
Step 3: Define the appropriate functions for stack operations such as push, pop, isEmpty, peek and size.Step 4:
Define the functions for queue operations like enqueue, dequeue, front, size.
Step 5: Create objects for stack and queue class.
Step 6: Call the methods and implement the operations.Step 7:stop

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())
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())
OUTPUT:

Stack operation
examples True
python
3
False
11.5
True
2

Queue operation
examples True
python
3
False
5
python
2

RESULT:

Thus the stack and queue ADTs are implemented using python classes.
EX.NO:2 RECURSIVE ALGORITHM- FIBONACCI SERIES
DATE:

AIM:
To implement recursive Fibonacci series algorithm in python

ALGORITHM:
Step 1: Start
Step 2: Read the number of terms (n) from the user.
Step 3: If the number of terms (n) is less than 0, print “Invalid Input”.
Step 4: Else, call the Fibonacci function recursively “n” times.
Step 5: Define the recursive function as:
If n is less than or equal to 1, return n value
Else, return Fibonacci(n-1) + fibonacci (n-2)
Step 6: Stop.

PROGRAM:

def recursive_fibonacci(n):
if n <= 1:
return n
else:
return(recursive_fibonacci(n-1) + recursive_fibonacci(n-2))
n_terms= int(input(“Enter the number of terms”))
if n_terms< 0:
print("Invalid input ! Please input a positive value")
elifn_terms ==0:
print("Fibonacci series:")
print(0)
else:
print("Fibonacci series:")
for i in range(n_terms):
print(recursive_fibonacci(i))
OUTPUT:

Fibonacci series
0,1,1,2,3,5,8,13,21,34

RESULT:
Thus, the Fibonacci series using recursion is implemented using python classes.
EX.NO:3 IMPLEMENT LIST ADT USING PYTHON
ARRAYS
DATE:

AIM:
To implement list ADT using python arrays.

ALGORITHM:
Step 1: Start
Step 2: Create an empty list even= []
Step 3: Use for loop to iterate the value
i

Step 4: Check whether the number is divisible by 2 using if condition


Step 5: If the condition is satisfied, then append the element/number to the list
Step 6: Stop.

PROGRAM:

Even= []
for i in range(11):
if i%2==0:
even.append(i)
print(“Even Numbers List:”,even)
OUTPUT:

Even Numbers List:


[0, 2, 4, 6, 8, 10]

RESULT:
Thus, the implementation of list ADT using python classes has been executed.
EX.NO:4 LINKED LIST IMPLEMENTATIONS OF LIST

DATE:

AIM:
To execute a code on linked list implementation of list in python.

ALGORITHM:

Step 1: Start
Step 2: Create classes Node and Linked List for creating a node and liking with the head node.
Step 3: Define proper methods in the class such as append, display for adding elements and display operations in
the linked list.
Step 4: Create an instance for the linked list class.
Step 5: Call the methods.
Step 6: Stop.

PROGRAM:

class Node:
def init (self, data):
self.data = data
self.next = None

class LinkedList:
def init (self):
self.head = None
self.last_node = None

def append(self, data):


if self.last_node is None:
self.head = Node(data)
self.last_node = self.head
else:
self.last_node.next = Node(data)
self.last_node = self.last_node.next

def display(self):
current = self.head
while current is not None:
print(current.data, end = ' ')
current = current.next

a_llist = LinkedList()
n = int(input('How many elements would you like to add? '))
for i in range(n):
data = int(input('Enter data item: '))
a_llist.append(data)
print('The linked list: ', end = '')
a_llist.display()

OUTPUT :

Enter data item: How many elements would you like to add?
5 Enter data item: 10
Enter data item: 11
Enter data item: 12
Enter data item 14
> 15
The linked list: 10 11 12 13 14 15
>

RESULT:

Thus the program for linked list implementation of list has been executed.
EX.NO:5A
STACK ADT
DATE:

AIM:
To write a python code to implement Stack ADT.

ALGORITHM:

Step1: Start
Step 2: Initialise top =0 and read the maximum size of the stack.
Step 3: Define stack methods such as CreateStack, Push, Pop,
IsEmpty. Step 4: Display the stack operations menu.
Step 5: Read the input from the user.
Step 6: Stop

PROGRAM:

top=0
mymax=eval(input("Enter Maximum size of stack:"))
def createStack():
stack=[]
return stack
def isEmpty(stack):
return len(stack)==0
def Push(stack,item):
stack.append(item)
print("Pushed to stack",item)
def Pop(stack):
if isEmpty(stack):
return "stack underflow"
return stack.pop()
stack=createStack()
while True:
print("1.Push")
print("2.Pop")
print("3.Display")
print("4.Quit")
ch=int(input("Enter your choice:"))
if ch==1:
if top<mymax:
item=input("Enter any
elements:") Push(stack,item)
top+=1
else:
print("Stack overflow")
elifch==2:
print(Pop(stack))
elifch==3:
print(stack)
else:
print("Exit")
break

OUTPUT:

Enter Maximum size of stack:3


1.Push
2.Pop
3.Display
4.Quit
Enter your choice:1
Enter any elements:100
Pushed to stack 100
1.Push
2.Pop
3.Display
4.Quit
Enter your choice:1
Enter any elements:200
Pushed to stack 200
1.Push
2.Pop
3.Display
4.Quit
Enter your choice:1
Enter any elements:300
Pushed to stack 300
1.Push
2.Pop
3.Display
4.Quit
Enter your
choice:3 ['100',
'200', '300']
1.Push
2.Pop
3.Display
4.Quit
Enter your
choice:2 300
1.Push
2.Pop
3.Display
4.Quit
Enter your
choice:3 ['100',
'200']
Enter your choice: 4

RESULT:
Thus the program for Stack ADT has been implemented.
EX.NO:5B QUEUE ADT

DATE:

AIM:
To write a python code to implement Queue ADT.
ALGORITHM:
Step1: Start
Step 2: Initialise front, rear =0 and read the maximum size of the queue.
Step 3: Define stack methods such as CreateQueue, Enqueue, Dequeue, IsEmpty.
Step 4: Display the Queue operations menu.
Step 5: Read the input from the user.
Step 6: Stop

PROGRAM:

front=0
rear=0
mymax=eval(input("Enter maximum size of queue:"))
def createQueue():
queue=[]
return
queue

def isEmpty(queue):
return len(queue)==0
def enqueue(queue,item):
queue.append(item)
print("Enqueued to queue",item)
def dequeue(queue):
if isEmpty(queue):
return "Queue is
empty" item=queue[0]
del queue[0]
return item
queue=createQueue()

while True:
print("1.Enqueue")
print("2.Dequeue")
print("3.Display")
print("4.Quit")
ch=int(input("Enter your choice:"))
if ch==1:
if rear<mymax:
item=input("Enter any
elements:") enqueue(queue,item)
rear+=1
else:
print("Queue is full")
elifch==2:
print(dequeue(queue))
elifch==3:
print(queue)
else:
print("Exit")
break
OUTPUT:

Enter Maximum size of queue:3


1. Enqueue
2. Dequeue
3.Display
4.Quit
Enter your choice:1
Enter any
elements:100
Enqueued to queue 100
1. Enqueue
2. Dequeue
3.Display
4.Quit
Enter your choice:1
Enter any
elements:200
Enqueued to queue 200
1. Enqueue
2. Dequeue
3. Display
4. Quit
Enter your choice:1
Enter any
elements:300
Enqueued to queue 300
1. Enqueue
2. Dequeue
3.Display
4.Quit
Enter your
choice:3 ['100',
'200', '300']
1. Enqueue
2. Dequeue
3.Display
4.Quit
Enter your choice:2
300
1. Enqueue
2. Dequeue
3.Display
4. Quit
Enter your choice:3
['100', '200']
Enter your choice: 4

RESULT:

Thus the program for Queue ADT has been implemented.


EX.NO:6A
APPLICATION OF STACK ADT
DATE:

AIM:
To write a python program to implement the application of Stack ADT – Infix to postfix expression
ALGORITHM:
Step 1: Start
Step 2: Create a class Stack and instantiate it.
Step 3: Define the stack methods.
Step 4: Define the function infix to postfix
evaluation Step 5: Print the postfix expression
Step 6: Stop.

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':
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()
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)

OUTPUT:

The postfix expression of infix expression A + B * C - D / E * H


is A B C * + D E /H *

RESULT:
Thus the program for infix to postfix expression is executed.
EX.NO:6B
APPLICATION OF QUEUE ADT
DATE:

AIM:
To write a python program to implement the application of Queue ADT – Round Robin Schedule.
ALGORITHM:

Step 1: Start
Step 2: Create a class Process and instantiate it.
Step 3: Define the Priority queue methods such as rotation and priority assignment.
Step 4: Read the process inputs and print the schedule output.
Step 6: Stop.

PROGRAM:

import random
import heapq

class Process:
pid = 0
def init (self, priority, time):
self.priority = priority
self.time = time
self.used = 0
self.pid =
Process.pid
Process.pid += 1

def lt (self, other):


return self.priority<other.priority

def priority(p):
heapq.heapify(p)
current_process = heapq.heappop(p)
counter = 0
while current_process:
counter += 1
current_process.priority -= 3
current_process.time -= 1
print('\n[{}]: Running process {}, priority: {}, also need: {}'.format(counter,
current_process.pid, current_process.priority,current_process.time))
for item in p:
print('Process {}, priority is {}, still needs time: {}'.format(item.pid,item.priority,item.time))
if current_process.time != 0:
heapq.heappush(p, current_process)
heapq.heapify(p)
if len(p) > 0:
current_process = heapq.heappop(p)
else:
break
return counter

def rotation(p):
rotation_time_length = 5
current_process =
p.pop(0) counter = 0
while current_process:
counter += 1
current_process.time -= 1
current_process.used += 1
print('\n[{}]: Running process {}, already occupied: {}, still need: {}'.format(counter,
current_process.pid,current_process.used,current_process.time))
for item in p:
print('Process {} still needs time: {}'.format(item.pid, item.time))
if current_process.time == 0:
if len(p):
current_process =
p.pop() else:
return counter
else:
if current_process.used == rotation_time_length:
current_process.used = 0
p.append(current_process)
current_process = p.pop()

def main():
method = input("\n>>> Process scheduling ALGORITHM.\nA. Priority ALGORITHM\tB. Round robin
ALGORITHM\n> ")
p = [Process(random.randrange(97,100), random.randrange(1, 21)) for i in range(random.randrange(4, 9))]
if method == 'A':
priority(p)
elif method == 'B':
rotation(p)
else:
print('\n[ERROR]: Input error')
print()

if name == ' main


': main()
OUTPUT:

[1] : Running process 0, already occupied: 1, still need: 5

Process 1 still needs time: 2


Process 2 still needs time: 12
Process 3 still needs time: 11
Process 4 still needs time: 18
Process 5 still needs time: 4
Process 6 still needs time: 6

RESULT:

Thus the program for round robin scheduling is executed.


EX.NO:6C APPLICATION OF LIST ADT

DATE:

AIM:
To write a python program to implement the application of Linked List ADT – Polynomial Addition.

ALGORITHM:
Step 1: Start
Step 2: Create a class Polynomial and instantiate it.
Step 3: Define the methods such as create_poly, show_poly and solve_poly for performing polynomial addition.
Step 4: Read the two polynomials as input and add both.
Step 6: Stop
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
while (temp != None) :
if (temp != self.head) :
print("+", temp.data, end = "")
else :
print(temp.data, end = "")
if (temp.power != 0) :
print("x^", temp.power, end = " ",sep = "")
temp = temp.next
print(end = "\n")
def addNode(self, data, power)
: if (self.head ==
None) :

self.head = Node(data, power)


else :

node = None
temp =
self.head
location = None
while (temp != None and temp.power>= power) :
location = temp
temp = temp.next
if (location != None and location.power == power) :
location.data = location.data + data
else :
node = Node(data,
power) if (location ==
None) :
node.next = self.head
self.head = node
else :
node.next = location.next
l
o
c
a
t
i
o
n
.
n
e
x
t

n
o
d
e
def addTwoPolynomials(self, other) :
RESULT = None
tail = None
node = None
first = self.head
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

if (tail == None) :
tail = node
else :
tail.next = node
tail = node
returnRESULT
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("\n Polynomial
A") poly1.display()
print(" Polynomial B")
poly2.display()
RESULT.head = poly1.addTwoPolynomials(poly2)
print(" RESULT")
RESULT.display()

if name == " main ": main()


OUTPUT:

3x^1 + 1x^2 + 3x^0 = 0

RESULT:
Thus the program for polynomial addition has been executed.
EX.NO:7A
SELECTION SORT
DATE:

AIM:
To write a python program to implement selection sort.
ALGORITHM:
Step 1: Start
Step 2: Read the input numbers for sorting.
Step 3: Perform the selection sort procedure as
:
The subarray which is already sorted.
Remaining subarray which is unsorted.
In every iteration of selection sort, the minimum element from the unsorted subarray is picked and moved
to the sorted subarray.
Step 4: Display the sorted elements
Step 5: Stop.

PROGRAM:

import sys
n=int(input(“enter the number of elements”))
A=[ ]
for i in range(n):
A.append(int(input()))
print(A)
for i in range(len(A)):
min_idx = i
for j in range(i+1, len(A)):
if A[min_idx] > A[j]:
min_idx = j

A[i], A[min_idx] = A[min_idx], A[i]

print ("Sorted array")


for i in range(len(A)):
print("%d" %A[i]),

OUTPUT:

Sorted array is:


11
22
33
44
55

RESULT:

Thus the program for selection sort has been executed.


EX.NO:7B
INSERTION SORT
DATE:

AIM:

To write a python program to implement insertion sort.


ALGORITHM:
Step 1: Start
Step 2: Read the input numbers for sorting.
Step 3: To sort an array of size n in ascending order:
3a: Iterate from arr[1] to arr[n] over the array.
3b: Compare the current element (key) to its predecessor.
3c: If the key element is smaller than its predecessor, compare it to the elements before. Move the greater
elements one position up to make space for the swapped element.Step 4: Display the sorted elements
Step 5: Display the sorted elements.
Step 6: Stop.

PROGRAM:

def insertionSort(arr):
for i in range(1, len(arr)):
key = arr[i]
j = i-1
while j >=0 and key <arr[j] :
arr[j+1] = arr[j]
j -= 1
arr[j+1] = key
lst=[]
n =int(input(“Enter the size of list”))
for i in range(n):
lst.append(int(input())
insertionSort(lst)
print ("Sorted array is:")
for i in range(n):
print ("%d" lst[i])

OUTPUT:

Enter the size of list


5 11 13 6 12
Sorted array is:
5
6
11
12
13

RESULT:

Thus the program for insertion sort has been executed.


EX.NO:7C
QUICK SORT
DATE:

AIM:
To write a python program to implement Quick sort.
ALGORITHM:
Step 1: Start
Step 2: Read the input numbers for sorting.
Step 3: To sort an array of size n in ascending order:
3a. Select the pivot element
3b. partition the array using pivot value
3c. quicksort left partition recursively
3d. quicksort right partition recursively
Step 4: Display the sorted elements.
Step 6: Stop.

PROGRAM:

def partition(arr,low,high):
i = ( low-1 )
pivot = arr[high]
for j in range(low , high):
if arr[j] <=
pivot: i =
i+1
arr[i],arr[j] = arr[j],arr[i]
arr[i+1],arr[high] = arr[high],arr[i+1]
return ( i+1 )
def quickSort(arr,low,high):
if low < high:
pi = partition(arr,low,high)
quickSort(arr, low, pi-1)
quickSort(arr, pi+1, high)
lst=[]
n = int(input('enter the elements'))
for i in range(n):
lst.append(int(input()))
print(lst)
quickSort(lst,0,n-1)
print ("Sorted array
is:") for i in range(n):
print (lst[i],end=" ")

OUTPUT:

Original Array: [4, 2, 7, 3, 1, 6]


Sorted Array: [1, 2, 3, 4, 6, 7]

RESULT:

Thus the program for Quick sort has been executed.


EX.NO:7D

DATE: LINEAR SEARCH

AIM:
To write a python program to implement Linear Search.
ALGORITHM:
Step 1: Start
Step 2: Read the numbers and the element to be searched.
Step 3: To search the particular number:
Repeat the search procedure for all the elements in the list:
if item == value
return its index
Step 4: Print the index of the element.
Step 5: Stop
PROGRAM:

#Linear Search
n=int(input("Enter the size of list"))
lst=[]
flag=False
print("Enter the elements")
for i in range(0,n):
lst.append(int(input()))
print(lst)
x=int(input("Enter the element to search"))
for i in range(0,n):
if x==lst[i]:
flag=True
break
if flag==True:
print("The element is found")
else:
print("The element is not found")

OUTPUT:
Element found at index: 3

RESULT:

Thus the program for Linear Search has been executed.


EX.NO:7E

DATE: BINARY SEARCH

AIM

To write a python program to implement Binary Search.


ALGORITHM
Step 1: Start
Step 2: Read the numbers and the element to be searched.
Step 3: To search the particular number:
Repeat the search procedure for all the elements in the list:
mid = (low + high)/2
if (x ==
arr[mid]) return
mid
else if (x > arr[mid])
low = mid + 1
else
high = mid – 1
Step 4: Print the index of the element.
Step 5: Stop.

PROGRAM:

def binary_search(data, target, low, high):


if low > high:
return False
else:
mid = (low + high) // 2
if target == data[mid]:
return True
elif target < data[mid]:
return binary_search(data, target, low, mid-1)
else:
return binary_search(data, target, mid + 1, high)
lst=[]
n =int(input("Enter the size of list"))
for i in range(n):
lst.append(int(input()))
lst.sort()
print(lst)
x=int(input("Enter the element to search"))
low=0
high=n-1
a=binary_search(lst,x,low,high)
if a==True:
print('Element found')
else:
print('Element Not found')

OUTPUT:
Element is present at index 1

RESULT:

Thus the program for Binary Search has been executed.


EX.NO: 8
HASH TABLES
DATE:

AIM:
To write a python program to implement Hash table.
ALGORITHM:

Step 1: Start
Step 2: Create class Node and linked list.
Step 3: Define the add, get and remove functions for the data.
Step 4: Create a class HashMap for implementing the hash table.
Step 5: Define the hash function as key%size, and define the functions for data position, removal and retrieval in
the hash table.
Step 6: Stop

PROGRAM:

class Node:
def init (self, key, val):
self.key = key
self.val = val
self.next = None
class LinkedList:
def init (self):
self.prehead = Node(None, None)
def search(self, key):
p = self.prehead.next
while p:
if p.key == key:
return p
p = p.next
return None
def add(self, key, val):
p = self.search(key)
if p:
p.val = val
else:
node = Node(key, val)
self.prehead.next, node.next = node, self.prehead.next
def get(self, key):
p = self.search(key)
if p:
return p.val
else:
return None
def remove(self, key):
prev = self.prehead
cur = prev.next
while cur:
if cur.key == key:
break
prev, cur = cur,
cur.next if cur:
prev.next =
cur.next def
serialize(self):
p = self.prehead.next
ret = []
while p:
ret.append([p.key, p.val])
p = p.next
return ret
class MyHashMap:
def init (self):
self.size = 1033
self.arr = [LinkedList() for _ in range(self.size)]
def _hash(self, key):
return key % self.size
def put(self, key,
value): h =
self._hash(key)
self.arr[h].add(key, value)
def get(self, key):
h = self._hash(key)
ret = self.arr[h].get(key)
if ret is not None:
return ret
else:
return -1
def remove(self, key):
h = self._hash(key)
self.arr[h].remove(key)
ob = MyHashMap()
ob.put(1, 1)
ob.put(2, 2)
print(ob.get(1))
print(ob.get(3))
ob.put(2, 1)
print(ob.get(2))
ob.remove(2)
print(ob.get(2))
ob = MyHashMap()
ob.put(1, 1)
ob.put(2, 2)
print(ob.get(1))
print(ob.get(3))
ob.put(2, 1)
print(ob.get(2))
ob.remove(2)
print(ob.get(2))
OUTPUT:

1
-1
1
-1

RESULT:

Thus the program for implementation of hash table has been executed.
EX.NO: 9A
BINARY TREE REPRESENTATION
DATE:

AIM:
To write a python program to implement Binary tree.
ALGORITHM:

Step 1: Start
Step 2: Create a class Node
Step 3: Define the insert method such that no element in the left side of the tree is greater and no element in the
right side of the tree is smaller than the root node.
Step 4: Define the print tree method.
Step 5: Call the functions using the class instance.
Step 6: Stop.

PROGRAM:

class Node:

def init (self, data):


self.left = None
self.right = None
self.data = data

def insert(self,
data): if self.data:
if data <self.data:
if self.left is
None:
self.left = Node(data)
else:
self.left.insert(data)
elif data >self.data:
if self.right is None:
self.right =
Node(data) else:
self.right.insert(data)
else:
self.data = data

def PrintTree(self):
if self.left:
self.left.PrintTree()
print( self.data),
if self.right:
self.right.PrintTree()
root = Node(27)
root.insert(14)
root.insert(35)
root.insert(31)
root.insert(10)
root.insert(19)
root.PrintTree()

OUTPUT:

10 14 19 27 31 35

RESULT:

Thus the program for implementation Binary tree representation has been executed.
EX.NO: 9B TREE TRAVERSAL ALGORITHAM

DATE:

AIM:

To write a python program to implement Tree traversal algorithms.

ALGORITHM:

Step 1: Start
Step 2: Create class Node.
Step 3: Define the pre order, post order and inorder methods for data.
Step 4: Call the functions using the instance of the class.
Step 5: Evaluate the traversal using recursive function call.
Step 6: Print every order of the traversal.
Step 6: Stop

PROGRAM:

class Node:
def init (self, item):
self.left = None
self.right = None
self.val = item
def inorder(root):
if root:
inorder(root.left)
print(str(root.val) + "->",
end='') inorder(root.right)

def postorder(root):
if root:
postorder(root.left)
postorder(root.right)
print(str(root.val) + "->",
end='')

def preorder(root):
if root:
print(str(root.val) + "->",
end='') preorder(root.left)
preorder(root.right)
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left =
Node(4)
root.left.right = Node(5)

print("Inorder traversal
") inorder(root)

print("\nPreorder traversal
") preorder(root)

print("\nPostorder traversal
") postorder(root)
OUTPUT:

Inorder traversal
4->2->5->1->3->
Preorder traversal
1->2->4->5->3->
Postorder traversal
4->5->2->3->1->

RESULT:

Thus, the program for implementation of tree traversals has been executed.
EX.NO: 10
BINARY SEARCH TREE
DATE:

AIM:

To implement a binary search tree in python.

ALGORITHM:

Step1: Start
Step 2: Create a class Node and instantiate.
Step 3: Define the insert method of the BST with proper condition for insertion.
Step 4: Create a binary search tree class.
Step 5: Define the inorder traversal.
Step 6: Stop

PROGRAM:

class Node:

def init (self, key):


self.key = key
self.left = None
self.right = None

def insert(self, key):

if self is None:
self =
Node(key)
return
if key <self.key:
if self.left:
self.left.insert(key)
else:
self.left = Node(key)
return
else:
if self.right:
self.right.insert(key)
else:
self.right = Node(key)
return

class binarySearchTree:
def init (self, key):
self.root = Node(key)

def insert(self, key):


self.root.insert(key)

def inorder(root):
if root:
inorder(root.left)
print(root.key)
inorder(root.right)

BST = binarySearchTree(6)

BST.insert(3)
BST.insert(9)
BST.insert(1)
BST.insert(5)
BST.insert(7)
BST.insert(11)
inorder(BST.root)

OUTPUT:

1
3
5
6
7
9
11

RESULT:

Thus the binary search tree has been implemented.


EX.NO: 11
HEAPS
DATE:

AIM:
To implement a min heap in python.
ALGORITHM:

Step 1: Start
Step 2: Create the class and instantiate.
Step 3: Define the methods for hepify, building a min heap.
Step 4: Define the methods for deleting from a heap.
Step 5: Create instances for the class.
Step 6: Call the methods to construct a min heap.
Step 7: Stop

PROGRAM:

class MinHeap:
def init (self):
self.heap_list = [0]
self.current_size = 0

def sift_up(self, i):


while i // 2 > 0:
if self.heap_list[i] <self.heap_list[i // 2]:
self.heap_list[i], self.heap_list[i // 2] = self.heap_list[i // 2],
self.heap_list[i] i = i // 2

def insert(self, k):


self.heap_list.append(k)
self.current_size += 1
self.sift_up(self.current_size)

def sift_down(self, i):


while (i * 2) <= self.current_size:
mc = self.min_child(i)

if self.heap_list[i] >self.heap_list[mc]:
self.heap_list[i], self.heap_list[mc] = self.heap_list[mc], self.heap_list[i]
i = mc

def min_child(self, i):


if (i * 2)+1 >self.current_size:
return i *
2 else:
if self.heap_list[i*2] <self.heap_list[(i*2)+1]:
return i * 2
else:
return (i * 2) + 1

def delete_min(self):
if len(self.heap_list) == 1:
return 'Empty heap'
root = self.heap_list[1]
self.heap_list[1] = self.heap_list[self.current_size]
*self.heap_list, _ =
self.heap_list self.current_size -= 1
self.sift_down(1)
return root
my_heap =
MinHeap()
my_heap.insert(5)
my_heap.insert(6)
my_heap.insert(7)
my_heap.insert(9)
my_heap.insert(13)
my_heap.insert(11)
my_heap.insert(10)
print(my_heap.delete_min())

OUTPUT:

RESULT:

Thus the program for heap construction has been executed.


EX.NO: 12A
GRAPH REPRESENTATION
DATE:

AIM:
To implement the graph data structure representation.
ALGORITHM:

Step 1: Start
Step 2: Create graph methods such as add_vertex, add_edge.
Step 3: Define the print graph method.
Step 4: Call the methods with arguments.
Step 5: Stop

PROGRAM:

def add_vertex(v):
global graph
global vertices_no
if v in graph:
print("Vertex ", v, " already exists.")
else:
vertices_no = vertices_no + 1
graph[v] = []

def add_edge(v1, v2, e):


global graph
if v1 not in graph:
print("Vertex ", v1, " does not exist.")
elif v2 not in graph:
print("Vertex ", v2, " does not exist.")
else:
temp = [v2, e]
graph[v1].append(temp)

def print_graph():
global graph
for vertex in graph:
for edges in graph[vertex]:
print(vertex, " -> ", edges[0], " edge weight: ", edges[1])

graph = {}
vertices_no = 0
add_vertex(1)
add_vertex(2)
add_vertex(3)
add_vertex(4)
add_edge(1, 2,
1)
add_edge(1, 3, 1)
add_edge(2, 3, 3)
add_edge(3, 4, 4)
add_edge(4, 1,
5) print_graph()
print ("Internal representation: ", graph)
OUTPUT:

1 -> 3 edge weight: 1


2 -> 3 edge weight: 3
3 -> 4
1 -> 2 edge weight: 1
edge weight: 4
4 -> 1 edge weight: 5
Internal representation: {1: [[2, 1], [3, 1]], 2: [[3, 3]], 3: [[4, 4]], 4: [[1, 5]]}

RESULT:

Thus the graph data structure has been implemented.


EX.NO: 12B
DEPTH FIRST SEARCH
DATE:

AIM:

To implement the depth first search algorithm for graph.

ALGORITHM:

Step 1: Start
Step 2: Create a graph using the dictionary in
python. Step 3: Define the depth first search method
:
if node not in visited:
print (node)
visited.add(node)
Step 4: Call the methods with arguments recursively.
Step 5: Stop

PROGRAM:
graph = {
'A' :
['B','C'],
'B' : ['D', 'E'],
'C' : ['F'],
'D' : [],
'E' : ['F'],
'F' : []
}
visited = set()
def dfs(visited, graph, node):
if node not in visited:
print (node)
visited.add(node)
for neighbour in graph[node]:
dfs(visited, graph, neighbour)
dfs(visited, graph, 'A')

OUTPUT:

A
B
D
E
F
C

RESULT:

Thus the depth first search algorithm for graph has been implemented.
EX.NO: 12C
BREATH FIRST SEARCH
DATE:

AIM:

To implement the breadth first search algorithm for graph.


ALGORITHM:

Step 1: Start
Step 2: Create a graph using the dictionary in python and two lists.
Step 3: Define the breadth first search method :
visited.append(node)
queue.append(node)

Step 4: Call the methods with arguments recursively.


Step 5: Stop
PROGRAM:
graph = {
'A' :
['B','C'],
'B' : ['D', 'E'],
'C' : ['F'],
'D' : [],
'E' : ['F'],
'F' : []
}
visited =
[] queue =
[]
def bfs(visited, graph, node):
visited.append(node)
queue.append(node)
while queue:
s = queue.pop(0)
print (s, end = " ")
for neighbour in graph[s]:
if neighbour not in visited:
visited.append(neighbour)
queue.append(neighbour)
bfs(visited, graph, 'A')

OUTPUT:

ABCDEF

RESULT:

Thus the program for breadth first traversal for a graph has been implemented.
EX.NO: 13
SINGLE SOURCE SHORTEST PATH ALGORITHM
DATE:

AIM:

To implement the single source shortest path algorithm for graph.

ALGORITHM:

Step 1: Start
Step 2: Create a graph using nested lists.
Step 3: Define the shortest path algorithm as :
1) Create a set (shortest path tree set) that keeps track of vertices included in shortest path tree, i.e.,
whose minimum distance from source is calculated and finalized.
2) Assign a distance value to all vertices in the input graph. Initialize all distance values as
INFINITE. Assign distance value as 0 for the source vertex so that it is picked first.
3) While sptSet doesn’t include all vertices
a) Pick a vertex u which is not there in sptSet and has minimum distance value.
b) Include u to sptSet.
c) Update distance value of all adjacent vertices of
u. Step 4: Call the methods with arguments recursively.
Step 5: Stop

PROGRAM:
import sys
def to_be_visited():
global visited_and_distance
v = -10
for index in range(number_of_vertices):
if visited_and_distance[index][0] == 0
\
and (v < 0 or visited_and_distance[index][1] <= \
visited_and_distance[v][1]):
v=
index return v

vertices = [[0, 1, 1, 0],


[0, 0, 1, 0],
[0, 0, 0, 1],
[0, 0, 0, 0]]
edges = [[0, 3, 4, 0],
[0, 0, 0.5, 0],
[0, 0, 0, 1],
[0, 0, 0, 0]]

number_of_vertices = len(vertices[0])

visited_and_distance = [[0, 0]]


for i in range(number_of_vertices-1):
visited_and_distance.append([0, sys.maxsize])

for vertex in range(number_of_vertices):

to_visit = to_be_visited()
for neighbor_index in range(number_of_vertices):
if vertices[to_visit][neighbor_index] == 1 and \
visited_and_distance[neighbor_index][0] == 0:
new_distance = visited_and_distance[to_visit][1] \
+ edges[to_visit][neighbor_index]

if visited_and_distance[neighbor_index][1] >new_distance:
visited_and_distance[neighbor_index][1] = new_distance

visited_and_distance[to_visit][0] = 1
i=0

print("The shortest distance of ",chr(ord('a') + i),\


" from the source vertex a is:",distance[1])
i=i+1

OUTPUT:

The shortest distance of a from the source vertex a is: 0


The shortest distance of b from the source vertex a is: 3
The shortest distance of c from the source vertex a is: 3.5
The shortest distance of d from the source vertex a is:4.5

RESULT:
Thus the program for single source shortest path algorithm has been implemented.
EX.NO: 14A MINIMUM SPANNING TREE -KRUSKAL’S ALGORITHM

DATE:

AIM:
To implement the Minimum spanning tree using kruskuls algorithm.

ALGORITHM:

Step 1: Start
Step 2: Create a class graph and create methods.
Step 3: Create the minimum spanning tree as,
Create a forest in such a way that each graph is a separate tree.
Create a priority queue Q that contains all the edges of the graph.
Repeat Steps 4 and 5 while Q is NOT EMPTY
Remove an edge from Q
IF the edge obtained in Step 4 connects two different trees, then Add it to the forest
ELSE
Discard the edge
Step 4: Print the minimum spanning tree which has been
generated. Step 5: Stop

PROGRAM:

from collections import defaultdict

class Graph:

def init (self, vertices):


self.V = vertices
self.graph = []
def addEdge(self, u, v, w):
self.graph.append([u, v,
w])

def find(self, parent, i):


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

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


xroot = self.find(parent,
x) yroot =
self.find(parent, y)

if rank[xroot] < rank[yroot]:


parent[xroot] = yroot
elif rank[xroot] > rank[yroot]:
parent[yroot] =
xroot else:
parent[yroot] =
xroot rank[xroot] +=
1

def KruskalMST(self):

RESULT = []
i=0
e=0

self.graph = sorted(self.graph, key=lambda item: item[2])

parent, rank = [ ], [ ]
for node in
range(self.V):
parent.append(node)
rank.append(0)

while e <self.V-1:
u, v, w = self.graph[i]
i += 1
x = self.find(parent,
u) y =
self.find(parent, v)

if x != y:
e += 1
RESULT.append([u, v, w])
self.union(parent, rank, x,
y)

print("Following are the edges in the constructed MST")


for u, v, weight in RESULT:
print("%d - %d = %d" % (u, v, weight))

g = Graph(4)
g.addEdge(0, 1, 10)
g.addEdge(0, 2, 6)
g.addEdge(0, 3, 5)
g.addEdge(1, 3, 15)
g.addEdge(2, 3,
4)
g.KruskalMST()
OUTPUT:

Following are the edges in the constructed MST


2-3=4
0-3=5
0 - 1 = 10

RESULT:

Thus the program for Minimum spanning tree using Kruskal algorithm has been implemented.
EX.NO: 14B MINIMUM SPANNING TREE -PRIM’S ALGORITHM

DATE:

AIM:

To implement the Minimum spanning tree using Prim’s algorithm.

ALGORITHM:

Step 1: Start
Step 2: Create a graph using the nested list.
Step 3: Create the minimum spanning tree as,
Initialize the minimum spanning tree with a vertex chosen at random.
Find all the edges that connect the tree to new vertices, find the minimum and add it to the tree
Keep repeating step above until we get a minimum spanning tree
Step 4: Print the minimum spanning tree which has been
generated. Step 5: Stop

PROGRAM:

INF = 9999999
V=5
G = [[0, 9, 75, 0, 0],
[9, 0, 95, 19, 42],
[75, 95, 0, 51, 66],
[0, 19, 51, 0, 31],
[0, 42, 66, 31, 0]]
selected = [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]):
y=j
print(str(x) + "-" + str(y) + ":" + str(G[x][y]))
selected[y] = True
no_edge += 1

OUTPUT:
Edge : Weight

0-1:9
1-3:19
3-4:31
3-2:51

RESULT:

Thus the program for minimum spanning tree using Prim’s algorithm has been implemented
Downloaded by visali soundrrajan13
(soundrrajanvisali@gmail.com)

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy