0% found this document useful (0 votes)
15 views100 pages

DSA Record

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

DSA Record

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

S.No Name of the Experiment Page No.

Mark Staff
signature

1. SIMPLE ADTS-PYTHON CLASSES

2. RECURSIVE ALGORITHM- FIBONACCI SERIES

3. IMPLEMENT LIST ADT USING PYTHON ARRAYS

4. LINKED LIST IMPLEMENTATIONS OF LIST

5(A). STACK ADT

5(B). QUEUE ADT

6(A). APPLICATION OF STACK ADT

6(B). APPLICATION OF QUEUE ADT

6(C). APPLICATION OF LIST ADT

7(A). SELECTION SORT

7(B). INSERTION SORT

7(C). QUICK SORT

7(D). LINEAR SEARCH

7(E). BINARY SEARCH

8. HASH TABLES

9(A). BINARY TREE REPRESENTATION


9(B). TREE TRAVERSAL ALGORITHAM

10. BINARY SEARCH TREE

11. HEAPS

12(A). GRAPH REPRESENTATION

12(B). DEPTH FIRST SEARCH

12(C). BREATH FIRST SEARCH

13. SINGLE SOURCE SHORTEST PATH ALGORITHM

14(A). MINIMUM SPANNING TREE -KRUSKAL’S ALGORITHM

14(B). MINIMUM SPANNING TREE -PRIM’S ALGORITHM


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

PAGE NO : 1

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

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

self.items = []

def isEmpty(self):

return self.items == []

def enqueue(self,item):

self.items.append(item)

2
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')

3
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())

4
OUTPUT:

Stack operation examples

True

python

False

11.5

True

Queue operation examples

True

python

False

python

Program Output& Viva Total


(3) Result (4) (10)
(3)

RESULT:

Thus the stack and queue ADTs are implemented using python classes.

5
EX.NO : 2

DATE : RECURSIVE ALGORITHM- FIBONACCI SERIES


PAGE NO :6

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.

6
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))

7
OUTPUT:

Fibonacci series

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

Program Output& Viva Total


(3) Result (4) (10)
(3)

RESULT:

Thus, the Fibonacci series using recursion is implemented using python classes.

8
EX.NO : 03

DATE : IMPLEMENT LIST ADT USING PYTHON ARRAYS


PAGE NO :9

AIM:

To implement list adt using python arrays

ALGORITHM:

1. The append() method is called on a ListADT object, with a single argument item.

2. The method begins by accessing the items attribute of the object, which is a list.

3. The append() method is then called on the items list, passing in the item argument as a
parameter.

4. item is added to the end of the list and the size of the list increases by 1.

5. The append() method exits and the updated items list is now stored as an attribute of the
ListADT object.

6. The other methods in the class ListADT works similarly and are simple implementation of the
python list functions like insert, remove, index, pop with an additional check of empty list in
is_empty() function.

9
PROGRAM:

class ListADT:

def init (self):

self.items = []

def is_empty(self):

return len(self.items) == 0

def size(self):

return len(self.items)

def append(self, item):

self.items.append(item)

def insert(self, index, item):

self.items.insert(index, item)

def remove(self, item):

self.items.remove(item)

def index(self, item):

return self.items.index(item)

def pop(self, index=-1):

return self.items.pop(index)

def str (self):

return str(self.items)

my_list = ListADT()

my_list.append(1)

my_list.append(2)

10
my_list.append(3)

print(my_list)

my_list.remove(2)

print(my_list)

my_list.pop()

print(my_list)

OUTPUT:

[1, 2, 3]

[1, 3]

[1]

Program Output& Viva Total


(3) Result (4) (10)
(3)

RESULT:

Thus the program implement list ADT using python arrays has been executed.

11
EX.NO : 4

DATE : LINKED LIST IMPLEMENTATIONS OF LIST


PAGE NO :12

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.

12
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? '))

13
for i in range(n):

data = int(input('Enter data item: '))

a_llist.append(data)

print('The linked list: ', end = '')

a_llist.display()

14
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

Program Output& Viva Total


(3) Result (4) (10)
(3)

RESULT:

Thus the program for linked list implementation of list has been executed.

15
EX.NO : 5(A)

DATE : STACK ADT


PAGE NO :15

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

16
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:")

17
Push(stack,item)

top+=1

else:

print("Stack overflow")

elifch==2:

print(Pop(stack))

elifch==3:

print(stack)

else:

print("Exit")

break

18
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

19
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

Program Output& Viva Total


(3) Result (4) (10)
(3)

RESULT:

Thus the program for Stack ADT has been implemented.

20
EX.NO : 5(B)

DATE : QUEUE ADT


PAGE NO :21

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

21
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")

22
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

23
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

24
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


Program Output& Viva Total
(3) Result (4) (10)
(3)

RESULT:

Thus the program for Queue ADT has been implemented.

25
EX.NO : 6(A)

DATE : APPLICATION OF STACK ADT


PAGE NO :26

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.

26
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':

27
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:

28
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 *

Program Output& Viva Total


(3) Result (4) (10)
(3)

RESULT:

Thus the program for infix to postfix expression is executed

29
EX.NO : 6(B)

DATE : APPLICATION OF QUEUE ADT


PAGE NO :30

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.

30
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,

31
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):

32
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()

33
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

Program Output& Viva Total


(3) Result (4) (10)
(3)

RESULT:

Thus the program for round robin scheduling is executed.

34
EX.NO : 6(C)

DATE : APPLICATION OF LIST ADT


PAGE NO :35

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

35
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

36
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

location.next = node

def addTwoPolynomials(self, other) :

RESULT = None

tail = None

node = None

37
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) :

38
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("\n Polynomial A")

poly1.display()

print(" Polynomial B")

poly2.display()

RESULT.head = poly1.addTwoPolynomials(poly2)

print(" RESULT")

RESULT.display()

if name == " main ": main()

39
OUTPUT:

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

Program Output& Viva Total


(3) Result (4) (10)
(3)

RESULT:

Thus the program for polynomial addition has been executed.

40
EX.NO : 7(A)

DATE : SELECTION SORT


PAGE NO :41

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.

41
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]),

42
OUTPUT:

Sorted array is:

11

22

33

44

55

Program Output& Viva Total


(3) Result (4) (10)
(3)

RESULT:

Thus the program for selection sort has been executed.

43
EX.NO : 7(B)

DATE : INSERTION SORT


PAGE NO :44

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.

44
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])

45
OUTPUT:

Enter the size of list

5 11 13 6 12

Sorted array is:

11

12

13

Program Output& Viva Total


(3) Result (4) (10)
(3)

RESULT:

Thus the program for insertion sort has been executed.

46
EX.NO : 7(C)

DATE : QUICK SORT


PAGE NO :47

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.

47
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=" ")

48
OUTPUT:

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

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

Program Output& Viva Total


(3) Result (4) (10)
(3)

RESULT:

Thus the program for Quick sort has been executed.

49
EX.NO : 7(D)

DATE : LINEAR SEARCH


PAGE NO :50

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

50
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")

51
OUTPUT:

Element found at index: 3

Program Output& Viva Total


(3) Result (4) (10)
(3)

RESULT:

Thus the program for Linear Search has been executed.

52
EX.NO : 7(E)

DATE : BINARY SEARCH


PAGE NO :53

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.

53
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')

54
OUTPUT:

Element is present at index 1

Program Output& Viva Total


(3) Result (4) (10)
(3)

RESULT:

Thus the program for Binary Search has been executed.

55
EX.NO : 8

DATE : HASH TABLES


PAGE NO :55

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

56
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)

57
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

58
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))

59
print(ob.get(3))

ob.put(2, 1)

print(ob.get(2))

ob.remove(2)

print(ob.get(2))

OUTPUT:

-1

-1

Program Output& Viva Total


(3) Result (4) (10)
(3)

RESULT:

Thus the program for implementation of hash table has been executed.

60
EX.NO : 9(A)

DATE : BINARY TREE REPRESENTATION


PAGE NO :61

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.

61
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:

62
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

Program Output& Viva Total


(3) Result (4) (10)
(3)

RESULT:

Thus the program for implementation Binary tree representation has been executed.

63
EX.NO : 9 (B)

DATE : TREE TRAVERSAL ALGORITHAM


PAGE NO :64

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

64
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)

65
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)

66
OUTPUT:

Inorder traversal

4->2->5->1->3->

Preorder traversal

1->2->4->5->3->

Postorder traversal

4->5->2->3->1->

Program Output& Viva Total


(3) Result (4) (10)
(3)

RESULT:

Thus, the program for implementation of tree traversals has been executed.

67
EX.NO : 10

DATE : BINARY SEARCH TREE


PAGE NO :68

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

68
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)

69
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)

70
OUTPUT:

11

Program Output& Viva Total


(3) Result (4) (10)
(3)

RESULT:

Thus the binary search tree has been implemented.

71
EX.NO : 11

DATE : HEAPS
PAGE NO :72

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

72
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):

73
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())

74
OUTPUT:

Program Output& Viva Total


(3) Result (4) (10)
(3)

RESULT:

Thus the program for heap construction has been executed.

75
EX.NO : 12(A)

DATE : GRAPH REPRESENTATION


PAGE NO :76

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

76
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])

77
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)

78
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]]}

Program Output& Viva Total


(3) Result (4) (10)
(3)

RESULT:

Thus the graph data structure has been implemented.

79
EX.NO : 12(B)

DATE : DEPTH FIRST SEARCH


PAGE NO :80

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

80
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')

81
OUTPUT:

Program Output& Viva Total


(3) Result (4) (10)
(3)

RESULT:

Thus the depth first search algorithm for graph has been implemented.

82
EX.NO : 12(C)

DATE : BREATH FIRST SEARCH


PAGE NO :83

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

83
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')

84
OUTPUT:

ABCDEF

Program Output& Viva Total


(3) Result (4) (10)
(3)

RESULT:

Thus the program for breadth first traversal for a graph has been implemented

85
EX.NO : 13

DATE : SINGLE SOURCE SHORTEST PATH ALGORITHM


PAGE NO :86

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

86
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])

87
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

88
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

Program Output& Viva Total


(3) Result (4) (10)
(3)

RESULT:

Thus the program for single source shortest path algorithm has been implemented.

89
EX.NO : 14(A)

DATE : MINIMUM SPANNING TREE -KRUSKAL’S ALGORITHM


PAGE NO :90

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

90
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

91
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

92
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()

93
OUTPUT:

Following are the edges in the constructed MST

2-3=4

0-3=5

0 - 1 = 10

Program Output& Viva Total


(3) Result (4) (10)
(3)

RESULT:

Thus the program for Minimum spanning tree using Kruskal algorithm has been implemented.

94
EX.NO : 14(B)

DATE : MINIMUM SPANNING TREE -PRIM’S ALGORITHM


PAGE NO :95

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

95
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]):

# not in selected and there is an edge

if minimum > G[i][j]:

minimum = G[i][j]

x=i

96
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

Program Output& Viva Total


(3) Result (4) (10)
(3)

RESULT:

Thus the program for minimum spanning tree using Prim’s algorithm has been implemented.

97
98

You might also like