0% found this document useful (0 votes)
9 views95 pages

Data Structures - Reg 2021

The document outlines various implementations of data structures and algorithms in Python, including simple ADTs like rectangles, Fibonacci sequences, doubly linked lists, singly linked lists, stacks, queues, and polynomial addition. Each section includes an aim, algorithm, program code, and output examples. The final sections focus on applications of lists and stacks, demonstrating polynomial operations and infix to postfix conversion.
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)
9 views95 pages

Data Structures - Reg 2021

The document outlines various implementations of data structures and algorithms in Python, including simple ADTs like rectangles, Fibonacci sequences, doubly linked lists, singly linked lists, stacks, queues, and polynomial addition. Each section includes an aim, algorithm, program code, and output examples. The final sections focus on applications of lists and stacks, demonstrating polynomial operations and infix to postfix conversion.
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/ 95

1) Implement Simple ADTS As Python Classes

Aim:-
To write program to implement simple adts in python classes.

Algorithm:-
Step 1:- start
Step 2:- create class rectangle
Step 3:- create methods like area and perimeter
Step 4:- declare breadth and length
Step 5:- create object for rectangle
Step 6:- call member function area and perimeter from class rectangle.
Step 7:-stop
Program:-
class Rectangle():
def_int_(self,breadth,length):
self.breadth=breadth
self.length=length
def area(self):
print(self.breadth*self.length)
def perimeter(self):
print(2*(self.breadth+self.length))
a=int(input("Enter length of the rectangle: "))
b=int(input("Enter breadth of the rectangle: "))
obj=Rectangle (a,b)
print("Area of rectangle ")
obj.area()
print("perimeter of rectangle")
obj.perimeter()
Output:-
Enter length of the rectangle: 3
Enter breadth of the rectangle: 2
Area of rectangle:
6
Perimeter of rectangle:
10
2) Implement recursive algorithms in Python
Aim:-
To write program to print a sequence of fibonacci using recursion.

Algorithm:-
Step 1:- start
Step 2:- declare function called Fibonacci
Step 3:-declare n for number of terms.
Step 4:-print the sequence of number
Step 5:- stop
Program:-
def Fibonacci(n):
if (n <=1):
return n
else:
return (fibonacci (n-1) + fibonacci (n-2))
print ("Enter number of terms")
n=int (input ())
print("fibonacci sequence is as follows...")
for i in range (n):
print (fibonacci (i))
Output:-
Enter number of terms
15
fibonacci sequence is as follows...
0
1
1
2
3
5
8
13
21
34
55
89
144
233
377
3) LIST ADT USING DOUBLY LINKED LIST

AIM :-
To Write A Python Program To Execute The Doubly Linked Lists

ALGORITHM:-
STEP 1: Start
STEP 2: Create a class
STEP 3: Create a header node and last node
STEP 4: Accept the user choice Insert, Delete and Display
STEP 5: Insert the new node
STEP 6: Delete the node from the list
STEP 7: Display the node
STEP 8: Stop
PROGRAM:-
Class Node:
Def init (self, data):
Self.item = data
Self.next = None
Self.prev = None
Class doublyLinkedList:
Def init (self):
Self.start_node = None
Def InsertToEmptyList(self, data):
If self.start_node is None:
New_node = Node(data)
Self.start_node = new_node
Else:
Print(“The list is empty”)
Def InsertToEnd(self, data):
If self.start_node is None:
New_node = Node(data)
Self.start_node = new_node
Return
N = self.start_node
While n.next is not None:
N = n.next
New_node = Node(data)
n.next = new_node
new_node.prev = n
Def DeleteAtStart(self):
If self.start_node is None:
Print(“The Linked list is empty, no element to delete”)
Return
If self.start_node.next is None:
Self.start_node = None
Return
Self.start_node = self.start_node.next
Self.start_prev = None;
Def delete_at_end(self):
If self.start_node is None:
Print(“The Linked list is empty, no element to delete”)
Return
If self.start_node.next is None:
Self.start_node = None
Return
N = self.start_node
While n.next is not None:
N = n.next
n.prev.next = None
Def Display(self):
If self.start_node is None:
Print(“The list is empty”)
Return
Else:
N = self.start_node
While n is not None:
Print(“Element is: “, n.item)
N = n.next
Print(“\n”)
NewDoublyLinkedList = doublyLinkedList()
NewDoublyLinkedList.InsertToEmptyList(10)
NewDoublyLinkedList.InsertToEnd(20)
NewDoublyLinkedList.InsertToEnd(30)
NewDoublyLinkedList.InsertToEnd(40)
NewDoublyLinkedList.InsertToEnd(50)
NewDoublyLinkedList.InsertToEnd(60)
NewDoublyLinkedList.Display()
NewDoublyLinkedList.DeleteAtStart()
NewDoublyLinkedList.DeleteAtStart()
NewDoublyLinkedList.Display()
OUTPUT:-
4) Linked List Implementations of List
Aim:
To Write a python program to implement Linked List

Algorithm:
Step1: Start
Step2: Create class Node
Step3: Create class SLL
Step4: Insert the element in the list
Step5: Display the element you want to delete
Step6: Display the element present in the linked list
Step7: Stop
Program:
class Node:
def __init__(self,data=None,next=None):
self.data=data
self.next=next
class SLL:
def __init__(self):
self.head=None
def create(self,data):
newNode=Node(data)
if(self.head):
temp=self.head
while(temp.next):
temp=temp.next
temp.next=newNode
else:
self.head=newNode
def display(self):
temp=self.head
while(temp):
s=str(temp.data)+"->"
print(s,end=" ")
temp=temp.next
print("NULL")
def insert_head(self,data):
newNode=Node(data)
if(self.head):
temp=self.head
newNode.next=temp
self.head=newNode
else:
self.head=newNode
def insert_last(self,data):
newNode=Node(data)
if(self.head):
temp=self.head
while(temp.next):
temp=temp.next
temp.next=newNode
else:
self.head=newNode
def insert(self,data):
newNode=Node(data)
print("After which node do you want to insert?");
middle_element=int(input())
if(self.head):
temp=self.head
while(temp.data!=middle_element):
temp=temp.next
newNode.next=temp.next
temp.next=newNode
else:
self.head=newNode
def delete(self):
temp=self.head
if(self.head==None):
print("The linked list is empty")
else:
print("Enter the element you want to delete:")
key=int(input())
while(temp.data!=key):
prev=temp
temp=temp.next
prev.next=temp.next
temp=None
def search(self):
temp=self.head
if(self.head==None):
print("The linked list is empty")
else:
print("Enter the element you want to search:")
key=int(input())
found=False
while(temp and found==False):
if(temp.data!=key):
temp=temp.next
else:
found=True
if(found):
print("The element is present in the linked list")
else:
print("The element is not present in the linked list")
obj=SLL()
obj.create(10)
obj.create(20)
obj.create(30)
print("The linked list is…")
obj.display()
obj.insert_head(9)
obj.display()
obj.insert_last(40)
obj.display()
obj.insert(35)
obj.display()
obj.delete()
obj.display()
obj.search()
Output:
5)i) Implementation of Stack ADT
Aim:-
To write program to implement stack ADT using python.

Algorithm:-
Step 1:- start
Step 2:- declare a empty stack.
Step 3:-print the options available in stack.
Step 4:-enter your choice from that.
Step 5:- in conditional statements enter the options like push,pop and display
Step 6:-stop
Program:-
# Program introduction statement
print("Simple STACK Data Structure Program")
# Initial empty STACK
stack = []
# Display Menu with Choices
while True:
print("\nSELECT APPROPRIATE CHOICE")
print("1. PUSH Element into the Stack")
print("2. POP Element from the Stack")
print("3. Display Elements of the Stack")
print("4. Exit")
choice = int(input("Enter the Choice:")) # Taking input from the user regarding choice
# USER enter option 1 then PUSH elements into the STACK
if choice == 1:
# append() function to PUSH elements into the STACK
stack.append("Monday") # PUSH element Monday
stack.append("Tuesday") # PUSH element Tuesday
stack.append("Wednesday") # PUSH element Wednesday
stack.append("Thursday") # PUSH element Thursday
stack.append("Friday") # PUSH element Friday
stack.append("Saturday") # PUSH element Saturday
stack.append("Sunday") # PUSH element Sunday
stack.append('8') # PUSH element 8
print('\nTotal 8 elements PUSH into the STACK')
# USER enter option 2 then POP one element from the STACK
elif choice == 2:
if len(stack) == 0: # Check whether STACK is Empty or not
print('The STACK is EMPTY No element to POP out')
# Display this ERROR message if STACK is Empty
else:
# pop() function to POP element from the STACK in LIFO order
print('\nElement POP out from the STACK is:')
print(stack.pop()) # Display the element which is POP out from the STACK

# USER enter option 3 then display the STACK


elif choice == 3:
if len(stack) == 0: # Check whether STACK is Empty or not
print('The STACK is initially EMPTY') # Display this message if STACK is Empty
else:
print("The Size of the STACK is: ",len(stack)) # Compute the size of the STACK
print('\nSTACK elements are as follows:')
print(stack) # Display all the STACK elements
# User enter option 4 then EXIT from the program
elif choice == 4:
break
# Shows ERROR message if the choice is not in between 1 to 4
else:
print("Oops! Incorrect Choice")
Output:-
>>>
Simple STACK Data Structure Program
SELECT APPROPRIATE CHOICE
1. PUSH Element into the Stack
2. POP Element from the Stack
3. Display Elements of the Stack
4. Exit
Enter the Choice:1
Total 8 elements PUSH into the STACK
SELECT APPROPRIATE CHOICE
1. PUSH Element into the Stack
2. POP Element from the Stack
3. Display Elements of the Stack
4. Exit
Enter the Choice:3
The Size of the STACK is: 7
STACK elements are as follows:
['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
5)ii) Implementation of queue ADT
Aim:-
To write program to implement stack ADT using python.

Algorithm:-
Step 1:- start
Step 2:- declare a empty queue.
Step 3:-print the options available in queue.
Step 4:-enter your choice from that.
Step 5:- in conditional statements enter the options like enqueue,dequeue and display
Step 6:-stop
Program:-
# Python program to
# demonstrate implementation of
# queue using queue module
from queue import Queue
# Initializing a queue
q = Queue(maxsize = 3)
# qsize() give the maxsize
# of the Queue
print(q.qsize())
q.put('a')
q.put('b')
q.put('c')
# Return Boolean for Full
# Queue
print("\nFull: ", q.full())
# Removing element from queue
print("\nElements dequeued from the queue")
print(q.get())
print(q.get())
print(q.get())
# Return Boolean for Empty
# Queue
print("\nEmpty: ", q.empty())
q.put(1)
print("\nEmpty: ", q.empty())
print("Full: ", q.full())
Output:-
>>>
Full: True

Elements dequeued from the queue


a
b
c

Empty: True

Empty: False
Full: False
Result:-
Thus the python program was executed and the output was verified successfully.
6)A) APPLICATIONS OF LIST

AIM :

To write a python program to implement the applications of list.

ALGORITHM :

STEP 1:Start

STEP 2: Set a pointer i to point to the first term in a polynomial A.

STEP 3: Set a pointer j to point to first term in a polynomial B.

STEP 4:Set a pointer k to point the first position in array C.

STEP 5:Read the number of terms of A polynomial in variable t1 and read the numbers of the
terms of A polynomial in variable 2.

STEP 6:.if exponent at ith position of A poly is equal to the exponent at jth position of
polynomial B then ,

STEP 6.1;Add the coefficients at that position from both the polynomial and store the
result in C arrays coefficient field at position k copy the exponent either pointed by i or
j at position k in C array.

STEP 6.2;Increment i, j and k to point to the next position in the array A, B and C.

STEP 6.3: Copy the coefficient at position j of B polynomial into coefficient field at
position k in C array.

STEP 6.4: Copy the exponent pointed by j into exponent field at position k in C array.

STEP 6.5: Increment j and k pointers to point to the next position in array B and C.

STEP 7: Copy the coefficient at position i of into the coefficient field at position k in C.

STEP 7.1: Copy the exponent pointed by i into the exponent field at position k in C
array.

STEP 7.2: Increment i and k to point to the next position in arrays A and C.
STEP 8: Copy the coefficient at position j of B into the coefficient field at position k
in C.

STEP 8.1: Copy the exponent pointed by j into exponent field at position k in C.

STEP 8.2:Increment j, k to point to the next position in B and C arrays.

STEP 9:Add the two given polynomials.

STEP 10: Display the complete array C .

STEP 11:End
PROGRAM :

class node:
def add(A, B, m, n):
size = max(m, n);
C=[0 for i in range(size)]
for i in range(0, m, 1):
C[i] = A[i]
for i in range(n):
C[il + B[i]
return C
def display(poly, n):
for i in range (n):
print(poly[i], end = "")
if (i!= 0):
print("x", i, end = "")
if (i!= n - 1):
print("+", end ="")

if name =="main":

A = [1, 1, 2, 3]
B = [0, 7,0, 5]
m = len(A)
n=len(B)
print("\nFirst polynomial is")
display(A, m)
print("\nSecond polynomial is")
display(B, n)
C=add(A, B, m, n)
size = max(m, n)
print("\n Addition of polymomial is'")
display(C, size)
OUTPUT :
6) b) Application of stack
Aim:
To write a python program for converting infix expression to postfix
form.

Algorithm:
Step 1: start
Step 2: create class as InfixPostfix
Step 3: check if the stack is empty
Step 4: return the top of the value of the stack
Step 5: pop the element from the stack
Step 6: then push the element to the stack
Step 7: check is the given character is operand
Step 8: check precedence of operator is less than top of stack or not
Step 9: use conditional statements
Step 10: declare a as self.pop()
Step11: declare s as *.join(self.postfix)
Step12:print (s)
Step13:print infix expression
Step14: stop.
Program:

class InfixPostfix:
def_init_(self):
self.top + -1
self.stack = []
self.postfix = []
self.precedence = {'+':1,
'-':1,
'.':2,
'/':2,
'^':3}
def isEmpty(self)
if(self.top == -1):
return True
else:
False
def peek(self):
return self.stack{-1}
def pop(self):
if not self.isEmpty():
self.top .= 1
return self.stack.pop()
else:
return "$"
def push(self,op):
self.top +=1
self.stack.append(op)
def notGreater(self,i):
try:
a = self.precedence{i}
b = self.precedence{self.peek()}
if a <= b:
return True
else:
return False
except KeyError:
return False
def convert(self,exp):
for ch in exp:
if self.isOperand(ch):
self.postfix.append(ch)
elif ch == '(':
self.push(ch)
elif ch == ')':
while((not self.isEmpty()) and self.peek()!= '('):
a = self.pop()
self.postfix.append(a)
if(not self.isEmpty() and self.peek() != '('):
return -1
else:
self.pop()
else:
while(not self.isEmpty() and self.notGreater(ch)):
self.postfix.append(self.pop())
self.push(ch)
while not self.isEmpty():
self.postfix.append(self.pop())
s = *.join(self.postfix)
print(s)
print("*program for conversion of infix to postfix*")
print("enter infix expression:")
exp = input()
obj = InfixPostfix()
print("the postfix expression is...")
obj.convert(exp)
Output:

**** Program for Conversion of Infix to Postfix form ****”)


Enter infix expression:
(a+b)*(c-d)
The postfix expression is…
ab+cd*
>>>
Result:
Thus the python program for converting infix to postfix form was executed and the
output was verified successfully.
6)iii) application of queue ADTs
Aim:-
To write program to implement application of queue ADTs.

Algorithm:-
Step 1:- start
Step 2:- declare a empty queue.
Step 3:-print the options available in queue.
Step 4:-enter your choice from that.
Step 5:- in conditional statements enter the options like enqueue,dequeue and display
Step 6:-stop
Program:-
class MyCircularQueue():
def __init__(self, k):
self.k = k
self.queue = [None] * k
self.head = self.tail = -1
# Insert an element into the circular queue
def enqueue(self, data):
if ((self.tail + 1) % self.k == self.head):
print("The circular queue is full\n")
elif (self.head == -1):
self.head = 0
self.tail = 0
self.queue[self.tail] = data
else:
self.tail = (self.tail + 1) % self.k
self.queue[self.tail] = data
# Delete an element from the circular queue
def dequeue(self):
if (self.head == -1):
print("The circular queue is empty\n")
elif (self.head == self.tail):
temp = self.queue[self.head]
self.head = -1
self.tail = -1
return temp
else:
temp = self.queue[self.head]
self.head = (self.head + 1) % self.k
return temp
def printCQueue(self):
if(self.head == -1):
print("No element in the circular queue")

elif (self.tail >= self.head):


for i in range(self.head, self.tail + 1):
print(self.queue[i], end=" ")
print()
else:
for i in range(self.head, self.k):
print(self.queue[i], end=" ")
for i in range(0, self.tail + 1):
print(self.queue[i], end=" ")
print()
# Your MyCircularQueue object will be instantiated and called as such:
obj = MyCircularQueue(5)
obj.enqueue(1)
obj.enqueue(2)
obj.enqueue(3)
obj.enqueue(4)
obj.enqueue(5)
print("Initial queue")
obj.printCQueue()
obj.dequeue()
print("After removing an element from the queue")
obj.printCQueue()
Output:-
>>>
Initial queue
12345
After removing an element from the queue
2345
Result:-
Thus the python program was executed and the output was verified successfully.
7)A)BINARY SEARCH

AIM:
To write a python program to implement binary search

ALGORITHM:
Step 1: start

Step 2: use if condition

Step 3: use if else ladder

Step 4: give array

Step 5:stop
PROGRAM :-
# Binary Search in python

def binarySearch(array, x, low, high):

if high >= low:

mid = low + (high - low)//2

# If found at mid, then return it

if array[mid] == x:

return mid

# Search the left half

elif array[mid] > x:

return binarySearch(array, x, low, mid-1)

# Search the right half

else:

return binarySearch(array, x, mid + 1, high)

else:

return -1

array = [3, 4, 5, 6, 7, 8, 9]

x=4

result = binarySearch(array, x, 0, len(array)-1)

if result != -1:

print("Element is present at index " + str(result))

else:

print("Not found")
OUTPUT:
7)B)LINEAR SEARCH

AIM:
To write a python program to implement linear search

ALGORITHM:
Step 1: start

Step 2: use if condition

Step 3: use if else

Step 4: give array

Step 5:stop
PROGRAM :-
def linearSearch(array, n, x):

for i in range(0, n):

if (array[i] == x):

return i

return -1

array = [2, 4, 0, 1, 9]

x=1

n = len(array)

result = linearSearch(array, n, x)

if(result == -1):

print("Element not found")

else:

print("Element found at index: ", result)


OUTPUT:

>>>
Element found at index: 3
7)C) Quick Sort
Aim:-
To write a python program to sort a list of elements using Quick sort.

Algorithm:
Step 1: start
Step 2:Input the elements of the list
Step 2: Display “Array before sorting”
Step 3: Repeat the following from i is equal to 0 until i is lesser than equal to high
Step 3.1: Display the value of a[i]
Step 4: Call quicksort()
Step 5: Display “Array after sorting”
Step 6: Display the sorted elements
Step 7: End
Program:-
def partition(array, low, high):
pivot = array[high]
i = low - 1
for j in range(low, high):
if array[j] <= pivot:
i=i+1
(array[i], array[j]) = (array[j], array[i])
(array[i + 1], array[high]) = (array[high], array[i + 1])
return i + 1
def quickSort(array, low, high):
if low < high:
pi = partition(array, low, high)
quickSort(array, low, pi - 1)
quickSort(array, pi + 1, high)
data = [8, 7, 2, 1, 0, 9, 6]
print("Unsorted Array")
print(data)
size = len(data)
quickSort(data, 0, size - 1)
print('Sorted Array in Ascending Order:')
print(data)
Output:-
7)d) IMPLEMENTATION OF MERGE SORT
Aim:-
To write a python program to implement merge sort.

Algorithm:-
Step 1: Input the total number of elements

Step 2: Input the elements in the list

Step 3: Call print()

Step 4: Call merge_sort()

Step 5: Call print()

Step 6: Return 0

Step 7: End

merge_sort(int a,int low, int high)

Step 1:Check whether low is greater than equal to high,if so

Step 1.1: Return

Step 2: Assign (low+high) to mid

Step 3: Call merge_sort(a, low, mid)

Step 4: Call merge_sort(a, mid+1, high)

Step 5: Call merge(a, low, mid, high)

Step 6:End

merge(int a[],int low, int mid, int high)

Step 1: Assign low to left

Step 2: Assign mid+1 to right

Step 3: Assign 0 to current

Step 4: Repeat the following until left is lesser than equal to mid and right is lesser than
equal to high

Step 4.1: Check if a[left] is lesser than equal to right,then

Step 4.1.1: Assign a[left] to temp[current]

Step 4.1.2: Increment the left value

Step 4.2: If not, do

Step 4.2.1: Assign a[right] to temp [current]

Step 4.2.2: Increment the right value


Step 4.3: Current value is incremented by one

Step 5: Check whether left is greater than mid

Step 5.1:Then repeat the following from i = right till i is lesser than equal to high

Step 5.1.1: Assign a[i] to temp[current]

Step 5.1.2:Increment the value of current Step

5.2: If not repeat the following from i is equal tp left till i is lesser than equal to mid Step

5.2.1: Assign a[i] to temp

Step 5.2.2: Increment the value of current

Step 6:Repeat the following from i is equal to 0 till is lesser than equal to (high-low)

Step 6.1: Assign temp[i] to a[low+1]

Step 7: End
Program:
def mergeSort(array):
if len(array) > 1:
r = len(array)//2
L = array[:r]
M = array[r:]
mergeSort(L)
mergeSort(M)
i=j=k=0
while i < len(L) and j < len(M):
if L[i] < M[j]:
array[k] = L[i]
i += 1
else:
array[k] = M[j]
j += 1
k += 1
while i < len(L):
array[k] = L[i]
i += 1
k += 1
while j < len(M):
array[k] = M[j]
j += 1
k += 1
# Print the array
def printList(array):
for i in range(len(array)):
print(array[i], end=" ")
print()
# Driver program
if __name__ == '__main__':
array = [6, 5, 12, 10, 9, 1]
mergeSort(array)
print("Sorted array is: ")
printList(array)
Output:
Sorted array is:
1 5 6 9 10 12
7)e) IMPLEMENTATION OF INSERTION SORT
Aim:-
To write a python program to implement insertion Sort.

Algorithm:-
Step 1: start

Step 2: declare function insertionSort

Step 3: declare array as data

Step 4: print sorted array

Step 5: call the function insertionSort.

Step 6: then print data

Step 7: End
Program:
def insertionSort(array):
for step in range(1, len(array)):
key = array[step]
j = step - 1
# Compare key with each element on the left of it until an element smaller than it is
found
# For descending order, change key<array[j] to key>array[j].
while j >= 0 and key < array[j]:
array[j + 1] = array[j]
j=j-1
# Place key at after the element just smaller than it.
array[j + 1] = key
data = [9, 5, 1, 4, 3]
insertionSort(data)
print('Sorted Array in Ascending Order:')
print(data)
Output:
Sorted Array in Ascending Order:
[1, 3, 4, 5, 9]
8)Implementation of Hash tables
Aim:-
To write program to Implementation of Hash tables.

Algorithm:-
Step 1:- start
Step 2:- declare a function display and linear_prob
Step 3:-declare hash table variable ad empty.
Step 4:-enter hash value in hash table.
Step 5:- display hash table
Step 6:-stop
Program:-
def display(a,n):
print("……………….")
print(" Hash Table ")
print("……………….")
for i in range(n):
print(i, "\t",a[i])
def Linear_prob(table,tsize,num):
key=num%tsize
while(table[key]!=-1):
key=(key+1)%tsize
table[key]=num
display(table,tsize)
SIZE=10;
hash_table=[];
print("Handling Hash Table Using Linear Problem")
i=0
for i in range(SIZE):
hash_table.append(-1)
ans= "y"
while ans== "y":
print("\n Enter The Number:")
num=int(input())
Linear_prob(hash_table,SIZE,num)
print("\n Do U Wish To Continue?(y/n)")
ans=input()[0]
Output:-
>>>
Handling Hash Table Using Linear Problem

Enter The Number:


10
……………….
Hash Table
……………….
0 10
1 -1
2 -1
3 -1
4 -1
5 -1
6 -1
7 -1
8 -1
9 -1

Do U Wish To Continue?(y/n)
Result:-
Thus the python program was executed and the output was verified successfully.
9) Tree representation and traversal algorithms
Aim:-
To write program to Implementation of Tree representation and traversal algorithms.

Algorithm:-
Step 1:- start
Step 2:- declare a function insert,inorder,preoder and postorder
Step 3:-show the available methods in program.
Step 4:-enter yr choice of method.
Step 5:- according to choice do the process.
Step 6:-stop
Program:-
class Node:
def init_(self, data):
self.valdata
self.left = None
self.right =None
def insert(root, data):
ch=""
if root is None:
return Node(data)
else:
print("Current node is: ",root.val," Where to attach a node?")
print(" If as a left child, press 1")
print(" If as a right child press r")
ch= input()[0]
if(ch=='r'):
root.right = insert(root.right, data)
elif (ch == 1):
root.left = insert(root.left, data)
else:
return root
return root
#The inorder function
def inorder(root):
if root:
inorder(root.left)
print(root.val,end="")
inorder(root.right)
def preorder(root):
if root:
printfroot.val.end=""
preorder(root.left)
preorder(root.right)
def postorder(root):
if root:
postorder(root.left)
postorder(root.right)
print(root.val,end="")
#Driver Code
print("Program for Implementation of Binary Search Tree")
I = None
ans = 'Y'
while(True):
print("in Main Menu")
print("1.Create")
print("2 Inorder")
print("3.Preorder")
print("4.Postorder")
print("Enter your choice: ")
choice = int(input())
if choice == 1:
while(ans =='Y'):
print("Enter the element: ")
num= int(input())
if(r==None):
r = Node(num)
else:
r=insert(r, num)
print("Do you want to continue?")
ans=input()[0]
elif choice == 2:
print("\n The inorder traversal is...")
inorder(r)
elif choice==3:
print("\n The preorder traversal is...")
preorder(r)
elif choice==4:
print("\n The postorder traversal is...")
postorder(r)
else:
print("Good Bye")
break
Output:-
>>>
Program for Implementation of Binary Search Tree
in Main Menu
1.Create
2 Inorder
3.Preorder
4.Postorder
Enter your choice:
10
Good Bye
Result:-
Thus the python program was executed and the output was verified successfully.
10)IMPLEMENTATION OF BINARY SEARCH
TREE

AIM:

To write a python program to implement Binary Search Tree.

ALGORITHM:

STEP 1: Start

STEP 2: Create a newNode with given value and set its left and right to “None”.

STEP 3: Check whether tree is Empty.

STEP 4: If the tree is Empty, then set set root to newNode.

STEP5: If the tree is Not Empty, then check whether value of newNode is smaller or largerthan
the node (here it is root node).

STEP 6: If newNode is smaller than or equal to the node, then move to its left child. If
newNode is larger than the node, then move to its right child.

STEP 7: Repeat the above step until we reach to a leaf node (ie., reach to “None”).

STEP 8: After reaching a leaf node, then insert the newNode as left child if newNode is
smaller else insert it as right child.

STEP 9: Read the search element from the user

STEP 10: Compare, the search element with the value of root node in the tree.

STEP 11: If both are matching, then display "Given node found!!!" and terminate the function

STEP 12: If both are not matching, then check whether search element is smaller or larger than
that node value.

STEP 13: If search element is smaller, then continue the search process in left subtree.
STEP 14: If search element is larger, then continue the search process in right subtree.

STEP 15: Repeat the same until we found exact element or we completed with a leaf node
PROGRAM:

class Node:
def init (self, key):
self.left = None
self.right = None
self.val = key
def insert(root, key):
if root is None:
return Node(key)
else:
if root.val == key:
return root
elif root.val < key:
root.right = insert(root.right, key)
else:
root.left = insert(root.left, key)
return root
def inorder(root):
if root:
inorder(root.left)
print(root.val)
inorder(root.right)
r = Node(50)
r = insert(r, 30)
r = insert(r, 20)
r = insert(r, 40)
r = insert(r, 70)
r = insert(r, 60)
r = insert(r, 80)
inorder(r)
OUTPUT:
RESULT:

Thus the python program to implement the Binary Search Tree was successfully
implemented and output is verified.
11) Implement Insertion Operation Of Heap In Python.
Aim:
To Write A Program To Implement A Heaps

Algorithm:
Step 1: Start
Step 2: Use Def Function
Step 3: Use Heap As Module
Step 4: Use If Condition
Step 5: Stop
Program:-
def heapify(Heap,n,i):
parent = int((i - 1)/ 2)
if (Heap[parent] > 0):
if (Heap[i]> Heap[parent]):
temp = Heap[i]#swap them
Heap[i]= Heap[parent]
Heap[parent]= temp
heapify(Heap,n,parent)
def Insert(Heap,Key):
global n
n =n+ 1 #size of heap is increased by 1
Heap.append(Key)
heapify(Heap,n,n-1)
def display(Heap,n):
print(Heap)
#Driver Code
a = []
print("\n Creating a heap")
print("\nHow many elements are there? ")
n = int(input())
for i in range(n):
print("\n Enter the elements: ")
num=int(input())
a.append(num)
print(" The heap is as follows...\n")
display(a, n)
print(" Enter the element to be inserted in the heap: ")
key = int(input())
Insert(a,key)
print(" After insertion the heap is as follows.....\n")
display(a, n)
Output:-
Creating a heap

How many elements are there?


5

Enter the elements:


1

Enter the elements:


2

Enter the elements:


3

Enter the elements:


4

Enter the elements:


5
The heap is as follows...

[1, 2, 3, 4, 5]
Enter the element to be inserted in the heap:
Result:-
Thus the python program for is executed successfully and output is verified.
12) Graph Representation And Traversal Algorithms

Aim:-

To write a python program for graph representation and traversal algorithms.

Algorithm:-
Step1: Start.

Step2: Pick any node ,visit the adjacent unvisited vertex, mark it as

visited,display it,and insert it in queue.

Step3: If there are no remaining adjacent vertices left,remove the

vertex from the queue.

Step4: Repeat step1 and step2 until the queue is empty or the desired

node is found.

Step5: Stop.
Program:-
def bfs(visited,graph,node):

visited.append(node)

queue.append(node)

while queue:

v1=queue.pop(0)

print(v1,end=" ")

for v2 in graph[v1]:

if v2 not in visited:

visited.append(v2)

queue.append(v2)

print("******Program for Displaying the graph using Breadth First Traversal******")

graph={'1':['2','3'],'2':['1','4'],'3':['1','4'],'4':['2','3']}

visited=[ ]

queue=[ ]

print("\n The graph is as follows")

n=len(graph)

i=1

for i in range(n):

print(list(graph.keys())[i],":",list(graph.values())[i])

print("Breadth First Search of graph is")

bfs(visited,graph,'1')
Output:-
Result:-
Thus the python program for implementation graph representation and traversal algorithm is
executed successfully and output is verified.
13) Implementation of shortest path algorithm
Aim:
To write a python program for implementing shortest path algorithm.

Algorithm:
Step 1: start
Step 2: Initialize distance list as all infinities
Step 3: set distance for source to be 0
Step 4: Initialize list of visited notes
Step 5: mark starting node as -1
Step 6: use for loop
Step 7: declare dist[v] as dist[u] + d
Step 8: print dist[v]
Step 9: declare graph values
Step10: find length of the graph
Step11: print the sample of the graph
Step12: print source
Step13: print shortest distance
Step14: stop
Program:

def Dijkstra(graph, source,n):


Inf = 9999999
dist = [Inf]*n
dist[source] = 0
visited = [False]*n
for k in range(n):
u = -1
for i in range(n):
if not visited[i] and (u = = -1 or dist[i] < dist[u]):
u=i
if dist[u] = = Inf:
break
visited[u] = True
for (v,d) in graph[u]:
if dist[u] + d < dist[v]:
dist[v] = dist[u] = d
print(“from”,source, “ to”,v, “ = ”,dist[v])
print(“\n ***** Program for implementation of Dijkstra’s Shortest Path Algorithm *****\n”)
graph = {
0: [(1,4),(2,8),(3,3)],
1: [(0,4),(2,1),(3,3)],
2: [(0,8),(1,1),(3,7),(4,3)],
3: [(1,3),(2,7),(4,8)],
4: [(2,3),(3,8)]
}
i=0
n=len(graph)
print(“The sample graph is as follows …”)
print(“…………………………………”)
print(“source->[(dest,dist)]”)
print(“…………………………………”)
for i in range(n):
print(i,”->”,graph[i])
print(“\n……………………………………..”)
print(“Shortest Distances …”)
print(“……………………………”)
Dijkstra(graph, 0,n)
Output:

***** Program for implementation of Dijkstra’s Shortest Path Algorithm *****


The Sample graph is as follows …
…………………............
source->[(dest,dist)]
………………………....
0 ->[(1,4),(2,8)]
1 ->[(0,4),(2,1),(3,3)]
2 ->[(0,8),(1,1),(3,7),(4,3)]
3 ->[(1,3),(2,7),(4,8)]
4 ->[(2,3),(3,8)]
……………………..
Shortest Distances …
……………………..
from 0 to 1 = 4
from 0 to 2 = 8
from 0 to 2 = 5
from 0 to 3 = 7
from 0 to 4 = 8
>>>
Result:
Thus the python program for implementing single source shortest path
using dijkstra’s algorithm was written and the output was verified
successfully.
14) Implementation of minimum spanning tree algorithms
Aim:-
To write program to Implementation of minimum spanning tree algorithms.

Algorithm:-
Step 1:- start
Step 2:- declare a class graph
Step 3:-declare a constructer to give values for v and graph .
Step 4:-declare a member function printmst, minkey and primmst .
Step 5:- in main program declare g object .
Step 6:- given values for graphs.
Step 7:-stop
Program:-
import sys # Library for INT_MAX
class Graph():
def __init__(self, vertices):
self.V = vertices
self.graph = [[0 for column in range(vertices)]
for row in range(vertices)]
# A utility function to print the constructed MST stored in parent[]
def printMST(self, parent):
print("Edge \tWeight")
for i in range(1, self.V):
print(parent[i], "-", i, "\t", self.graph[i][parent[i]])
def minKey(self, key, mstSet):
# Initialize min value
min = sys.maxsize
for v in range(self.V):
if key[v] < min and mstSet[v] == False:
min = key[v]
min_index = v
return min_index
def primMST(self):
# Key values used to pick minimum weight edge in cut
key = [sys.maxsize] * self.V
parent = [None] * self.V # Array to store constructed MST
# Make key 0 so that this vertex is picked as first vertex
key[0] = 0
mstSet = [False] * self.V
parent[0] = -1
for cout in range(self.V):
u = self.minKey(key, mstSet)
mstSet[u] = True
for v in range(self.V):
if self.graph[u][v] > 0 and mstSet[v] == False and key[v] >
self.graph[u][v]:
key[v] = self.graph[u][v]
parent[v] = u
self.printMST(parent)
# Driver's code
if __name__ == '__main__':
g = Graph(5)
g.graph = [[0, 2, 0, 6, 0],
[2, 0, 3, 8, 5],
[0, 3, 0, 0, 7],
[6, 8, 0, 0, 9],
[0, 5, 7, 9, 0]]
g.primMST()
Output:-
>>>
Edge Weight
0-1 2
1-2 3
0-3 6
1-4 5
Result:-
Thus the python program was executed and the output was verified successfully.

You might also like