DSA Rec-1

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 92

PRINCE SHRI VENKATESHWARA

PADMAVATHY ENGINEERING COLLEGE


PONMAR, CHENNAI - 600 048.

DEPARTMENT OF INFORMATION TECHNOLOGY


(B.TECH – III SEMESTER)
CS3281-DATA STRUCTURES LABORATORY
(2022– 2023)

NAME : _____________________________

REG. NO : _____________________________

BRANCH : _____________________________
PRINCE SHRI VENKATESHWARA PADMAVATHY
ENGINEERING COLLEGE
PONMAR, CHENNAI- 600 048.

Name : ………………………………………………

Register No : ………………………………………………

Semester : ………………………………………………

Branch : ………………………………………………

Certified that this is a Bonafide Record of the work done

by the above student in the Laboratory CS3281-DATA


STRUCTURES Laboratory during the year 2022 - 2023.

Submitted for Practical Examination held on …………….

Signature of Faculty In-Charge Signature of Principal

Internal Examiner External Examiner


INDEX

EX.NO. DATE NAME OF THE TITLE PAGE NO. SIGNATURE

1. Implement simple ADTs as Python


classes
2. Implement recursive algorithms in
Python
3. Implement List ADT using Python
arrays
4. Linked list implementation 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
12. Graph representation and
Traversal algorithms
13. Implementation of single source
shortest path algorithm
14. Implementation of minimum
spanning tree algorithms
15. Red Black Tree

16. Single Threaded Binary Search


Tree
1. IMPLEMENT SIMPLE ADTs AS PYTHON CLASSES

AIM:

To write a python program to Implement simple ADTs as Python classes.

ALGORITHM:

Step 1:Start Step 2:Create a class Rectangle.

Step 3:Initializing self.height=0,self.width=0.

Step 4:Defining perimeter and area

Step 5:Assigning ret.height=10,ret.width=5.

Step 6:Print the values of perimeter and area.

Step 7:End the program.

PROGRAM:

class Rectangle:

def __init__(self):

self.height=0

self.width=0

# functions(operations)

def perimeter(self):

return (self.height*2)+(self.width*2)

def area(self):

return self.height*self.width

ret = Rectangle()

ret.height = 10;

ret.width = 5;

print("Perimeter = ",ret.perimeter())

print("Area = ",ret.area())
OUTPUT:

RESULT:

Thus,the program for implement simple ADTs as Python classes has been executed successfully.
2. IMPLEMENT RECURSIVE ALGORITHMS IN PYTHON

A.FACTORIAL

AIM:

To write a python program to find the factorial of a number using recursion.

ALGORITHM:

Step -1: Start the program.

Step-2: Define a function factorial.

Step-3: Check the number is equal to 1 or not.

Step-4: If it is equal to 1 then return 1.

Step-5: Else return(x*factorial(x-1)).

Step-6: Get the number to calculate the factorial.

Step-7: Print.

Step-8: Stop the program.

PROGRAM:
def factorial(x):

"""This is a recursive function

to find the factorial of an integer"""

if x == 1:

return 1

else:

return (x * factorial(x-1))

num = 3

print("The factorial of", num, "is", factorial(num))


OUTPUT:

RESULT:

Thus,the program for implement recursive algorithms of Factorial in Python has been executed
successfully
B.SUM OF SEQUENCE

AIM:

To write a python program to find the sum of a sequence using recursion.

ALGORITHM:

Step-1: Start the program

Step-2: Define the function sum

Step-3: Initialize total=0

Step-4: Using for loop for index in range n+1, total=total+index

Step-5: Return total

Step-6: Call the function sum(n) and print the result.

Step-7: Stop the program.

PROGRAM:

def sum(n):

total = 0

for index in range(n+1):

total += index

return total

result = sum(100)

print(result)

OUTPUT:

RESULT:

Thus,the program for implement recursive algorithms of sum of sequence in Python has been
executed successfully.
3. IMPLEMENT LIST ADT USING PYTHON ARRAYS

AIM:

To write a python program to implement the python array using list.

ALGORITHM:

Step 1:Start the program.

Step 2:Import array library.

Step 3:Print the array values and then accessing the array element from index 2.

Step 4:Insert an element in the array of index 3 and 4(400,150) respectively,then print the inserted
element.

Step 5:Delete an element from the array (150) and then print.

Step 6:Traversing the elements from the array and then print.

Step 7:End the program.

PROGRAM:

import array

balance=array.array('i',[100,200,300])

print("the array given values")

print(balance)

print("accessing of an array element from index[2]:")

print(balance[2])

print("-----------inserting an element---------------")

balance.insert(3,400)

balance.insert(4,150)

print("after insertion")

print(balance)

print("accessing the index value of an element:")

print("------------deleting an element from a array------------")

balance.remove(150)
print(balance)

print("------------traverse array-------------")

for x in balance:

print("array element:")

print(x)

OUTPUT:

RESULT:

Thus,the program for implementing list ADT using array in Python has been executed successfully.
4. LINKED LIST IMPLEMENTATIONS OF LIST

AIM:

To write a python program to implement linked list.

ALGORITHM:

Step 1:Start the program.

Step 2:Create the head node.

Step 3:Add nodes to the head node and insert the values.

Step 4:Append new nodes and make the previous node to point the current node.

Step 5:The process continues till last node.

Step 6:The last node has null pointer.

Step 7:Traverse through the list.

Step 8:Display the elements.

Step 9:Stop the program.

PROGRAM:

A.SINGLY LINKED LIST

Import os

From typing import NewType

Class _Node:

‘’’

Creates a Node with two fields:

1. element (accesed using ._element)

2. link (accesed using ._link)

‘’’

__slots__ = ‘_element’, ‘_link’

Def __init__(self, element, link):

‘’’

Initialses _element and _link with element and link respectively.


‘’’

Self._element = element

Self._link = link

Class LinkedList:

‘’’

Consists of member funtions to perform different

Operations on the linked list.

‘’’

Def __init__(self):

‘’’

Initialses head, tail and size with None, None and 0 respectively.

‘’’

Self._head = None

Self._tail = None

Self._size = 0

Def __len__(self):

‘’’

Returns length of linked list

‘’’

Return self._size

Def isempty(self):

‘’’

Returns True if linked list is empty, otherwise False.

‘’’

Return self._size == 0

Def addLast(self, e):

‘’’

Adds the passed element at the end of the linked list.

‘’’
Newest = _Node(e, None)

If self.isempty():

Self._head = newest

Else:

Self._tail._link = newest

Self._tail = newest

Self._size +=1

Def addFirst(self, e):

‘’’

Adds the passed element at the beginning of the linked list.

‘’’

Newest = _Node(e, None)

If self.isempty():

Self._head = newest

Self._tail = newest

Else:

Newest._link = self._head

Self._head = newest

Self._size += 1

Def addAnywhere(self, e, index):

‘’’

Adds the passed element at the passed index position of the linked list.

‘’’

Newest = _Node(e, None)

I = index – 1

P = self._head

If self.isempty():

Self.addFirst€

Else:
For I in range(i):

P= p._link

Newest._link = p._link

p._link = newest

print(“Added Item at index {index}!\n\n”)

self._size += 1

def removeFirst(self):

‘’’

Removes element from the beginning of the linked list.

Returns the removed element.

‘’’

If self.isempty():

Print(“List is Empty. Cannot perform deletion operation.”)

Return

E = self._head._element

Self._head = self._head._link

Self._size = self._size – 1

If self.isempty():

Self._tail = None

Return e

Def removeLast(self):

‘’’

Removes element from the end of the linked list.

Returns the removed element.

‘’’

If self.isempty():

Print(“List is Empty. Cannot perform deletion operation.”)

Return

P = self._head
If p._link == None:

E = p._element

Self._head = None

Else:

While p._link._link != None:

P = p._link

E = p._link._element

p._link = None

self._tail = p

self._size = self._size – 1

return e

def removeAnywhere(self, index):

‘’’

Removes element from the passed index position of the linked list.

Returns the removed element.

‘’’

P = self._head

I = index – 1

If index == 0:

Return self.removeFirst()

Elif index == self._size – 1:

Return self.removeLast()

Else:

For x in range(i):

P = p._link

E = p._link._element

p._link = p._link._list

self._size -= 1

return e
def display(self):

‘’’

Utility function to display the linked list.

‘’’

If self.isempty() == 0:

P = self._head

While p:

Print(p._element, end=’’)

P = p._link

Print(“NULL”)

Else:

Print(“Empty”)

Def search(self, key):

‘’’

Searches for the passed element in the linked list.

Returns the index position if found, else -1.

‘’’

P = self._head

Index = 0

While p:

If p._element == key:

Return index

P = p._link

Index += 1

Return -1

Def options():

‘’’

Prints Menu for operations

‘’’
Options_list = [‘Add Last’, ‘Add First’, ‘Add Anywhere’,

‘Remove First’, ‘Remove Last’, ‘Remove Anywhere’,

‘Display List’, ‘Print Size’, ‘Search’, ‘Exit’]

Print(“MENU”)

For I, option in enumerate(options_list):

Print(f’{I + 1}. {option}’)

Choice = int(input(“Enter choice: “))

Return choice

Def switch_case(choice):

‘’’

Switch Case for operations

‘’’

If choice == 1:

Elem = int(input(“Enter Item: “))

L.addLast(elem)

Print(“Added Item at Last!\n\n”)

Elif choice == 2:

Elem = int(input(“Enter Item: “))

L.addFirst(elem)

Print(“Added Item at First!\n\n”)

Elif choice == 3:

Elem = int(input(“Enter Item: “))

Index = int(input(“Enter Index: “))

L.addAnywhere(elem, index)

Elif choice == 4:

Print(“Removed Element from First:”, L.removeFirst())

Elif choice == 5:

Print(“Removed Element from last:”, L.removeLast())


Elif choice == 6:

Index = int(input(“Enter Index: “))

Print(f”Removed Item: {L.removeAnywhere(index)} !\n\n”}

Elif choice == 7:

Print(“List: “, end=’’)

L.display()

Print(“\n”)

Elif choice == 8:

Print(“Size:”, len(L))

Print(“\n”)

Elif choice == 9:

Key = int(input(“Enter item to search: “))

If L.search(key) >= 0:

Print(f”Item {key} found at index position{L.search(key)}\n\n”)

Else:

Print(“Item not in the list\n\n”)

Elif choice == 10:

Import sys

Sys.exit()

If __name__ == ‘__main__’:

L = LinkedList()

While True:

Choice = options()

Switch_case(choice)

OUTPUT:

MENU

1. Add Last
2. Add First

3. Add Anywhere

4. Remove First

5. Remove Last

6. Remove Anywhere

7. Display List

8. Print Size

9. Search

10. Exit

Enter choice: 1

Enter Item: 23

Added Item at Last!

RESULT:

Thus,the program for implement singly linked list in Python has been executed successfully.
B. DOUBLY LINKED LIST

Import os

Class _Node:

‘’’

Creates a Node with three fields:

1. element (accessed using ._element)

2. link (accessed using ._link)

3. prev (accessed using ._prev)

‘’’

__slots__ = ‘_element’, ‘_link’, ‘_prev’

Def __init__(self, element, link, prev):

‘’’

Initialses _element, _link and _prev with element, link and prev respectively.

‘’’

Self._element = element

Self._link = link

Self._prev = prev

Class DoublyLL:

‘’’

Consists of member funtions to perform different

Operations on the doubly linked list.

‘’’

Def __init__(self):

‘’’

Initialises head, tail and size with None, None and 0 respectively.

‘’’

Self._head = None

Self._tail = None

Self._size = 0
Def __len__(self):

‘’’

Returns length of linked list

‘’’

Return self._size

Def isempty(self):

‘’’

Returns True if doubly linked list is empty, otherwise False.

‘’’

Return self._size == 0

Def addLast(self, e):

‘’’

Adds the passed element at the end of the doubly linked list.

‘’’

Newest = _Node(e, None, None)p

If self.isempty():

Self._head = newest

Else:

Self._tail._link = newest

Newest._prev = self._tail

Self._tail = newest

Self._size += 1

Def addFirst(self, e):

‘’’

Adds the passed element at the beginning of the doubly linked list.

‘’’

Newest = _Node(e, None, None)

If self.isempty():

Self._head = newest
Self._tail = newest

Else:

Newest._link = self._head

Self._head._prev = newest

Self._head = newest

Self._size += 1

Def addAnywhere(self, e, index):

‘’’

Adds the passed element at the passed index position of the

Doubly linked list.

‘’’

If index >= self._size:

Print(f’Index value out of range, it should be between 0 – {self._size – 1}’)

Elif self.isempty():

Print(“List was empty, item will be added at the end”)

Self.addLast€

Elif index == 0:

Self.addFirst€

Elif index == self._size – 1:

Self.addLast€

Else:

Newest = _Node(e, None, None)

P = self._head

For _ in range(index – 1):

P = p._link

Newest._link = p._link

p._link._prev = newest

newest._prev = p

p._link = newest
self._size += 1

def removeFirst(self):

‘’’

Removes element from the beginning of the doubly linked list.

Returns the removed element.

‘’’

If self.isempty():

Print(‘List is already empty’)

Return

E = self._head._element

Self._head = self._head._link

Self._size -= 1

If self.isempty():

Self._tail = None

Else:

Self._head._prev = None

Return e

Def removeLast(self):

‘’’

Removes element from the end of the doubly linked list.

Returns the removed element.

‘’’

If self.isempty():

Print(“List is already empty”)

Return

E = self._tail._element

Self._tail = self._tail._prev

Self._size -= 1

If self.isempty():
Self._head = None

Else:

Self._tail._link = None

Return e

Def removeAnywhere(self, index):

‘’’

Removes element from the passed index position of the

Doubly linked list.

Returns the removed element.

‘’’

If index >= self._size:

Print(f’Index value out of range, it should be between 0 – {self._size – 1}’)

Elif self.isempty():

Print(“List is empty”)

Elif index == 0:

Return self.removeFirst()

Elif index == self._size – 1:

Return self.removeLast()

Else:

P = self._head

For _ in range(index – 1):

P = p._link

E = p._link._element

p._link = p._link._link

p._link._prev = p

self._size -= 1

return e

def display(self):

‘’’
Utility function to display the doubly linked list.

‘’’

If self.isempty():

Print(“List is Empty”)

Return

P = self._head

Print(“NULL>”, end=’’)

While p:

Print(p._element, end=”>”)

P = p._link

Print(“NULL”)

Print(f”\nHead : {self._head._element}, Tail : {self._tail._element}”)

Def options():

‘’’

Prints Menu for operations

‘’’

Options_list = [‘Add Last’, ‘Add First’, ‘Add Anywhere’,

‘Remove First’, ‘Remove Last’, ‘Remove Anywhere’,

‘Display List’, ‘Exit’]

Print(“MENU”)

For I, option in enumerate(options_list):

Print(f’{I + 1}. {option}’)

Choice = int(input(“Enter choice: “))

Return choice

Def switch_case(choice):

‘’’

Switch Case for operations

‘’’

Os.system(‘cls’)
If choice == 1:

Elem = int(input(“Enter Item: “))

DL.addLast(elem)

Print(“Added Item at Last!\n\n”)

Elif choice == 2:

Elem = int(input(“Enter Item: “))

DL.addFirst(elem)

Print(“Added Item at First!\n\n”)

Elif choice == 3:

Elem = int(input(“Enter Item: “))

Index = int(input(“Enter Index: “))

DL.addAnywhere(elem, index)

Elif choice == 4:

Print(“Removed Element from First:”, DL.removeFirst())

Elif choice == 5:

Print(“Removed Element from last:”, DL.removeLast())

Elif choice == 6:

Index = int(input(“Enter Index: “))

Print(f”Removed Item: {DL.removeAnywhere(index)} !\n\n”)

Elif choice == 7:

Print(“List:”)

DL.display()

Print(“\n”)

Elif choice == 8:

Import sys

Sys.exit()

If __name__ == ‘__main__’:

DL = DoublyLL()

While True:
Choice = options()

Switch_case(choice)

OUTPUT:

MENU

1. Add Last

2. Add First

3. Add Anywhere

4. Remove First

5. Remove Last

6. Remove Anywhere

7. Display List

8. Exit

Enter choice: 2

Enter Item: 34

Added Item at First!

MENU

1. Add Last

2. Add First

3. Add Anywhere

4. Remove First

5. Remove Last

6. Remove Anywhere

7. Display List

8. Exit

Enter choice: 1

Enter Item: 2

Added Item at Last!


MENU

1. Add Last

2. Add First

3. Add Anywhere

4. Remove First

5. Remove Last

6. Remove Anywhere

7. Display List

8. Exit

Enter choice: 7

List:

NULL>34>2>NULL

RESULT:

Thus,the program for implement doubly linked list in Python has been executed successfully.
5. IMPLEMENTATION OF STACK AND QUEUE ADTs

STACK

AIM:

To write a python program to implement stack.

ALGORITHM:

Step 1:Start the program.

Step 2:Get the size from user and create the stack as list.

Step 3:Using push function,add element to the stack.

Step 4:Using pop function,pop element from the stack.

Step 5:get the choice from user whether to choose push,pop,display or exit.

Step 6:According to the users choice,call the respective function.

Step 7:If user’s choice is exit,stop the loop.

Step 8:Stop the program.

PROGRAM:.

Class Stack:

# Constructor to initialize the stack

Def __init__(self, size):

Self.arr = [None] * size

Self.capacity = size

Self.top = -1

# Function to add an element `x` to the stack

Def push(self, x):

If self.isFull():

Print(“Stack Overflow!! Calling exit()…”)

Exit(1)

Print(“Inserting”, x, “into the stack…”)

Self.top = self.top + 1
Self.arr[self.top] = x

# Function to pop a top element from the stack

Def pop(self):

# check for stack underflow

If self.isEmpty():

Print(“Stack Underflow!! Calling exit()…”)

Exit(1)

Print(“Removing”, self.peek(), “from the stack”)

#decrease stack size by 1 and (optionally) return the popped element

Top = self.arr[self.top]

Self.top = self.top – 1

Return top

# Function to return the top element of the stack

Def peek(self):

If self.isEmpty():

Exit(1)

Return self.arr[self.top

# Function to return the size of the stack

Def size(self):

Return self.top + 1

# Function to check if the stack is empty or not

Def isEmpty(self):

Return self.size() == 0

# Function to check if the stack is full or not

Def isFull(self):

Return self.size() == self.capacity

If __name__ == ‘__main__’:

Stack = Stack(3)
Stack.push(1) # Inserting 1 in the stack

Stack.push(2) # Inserting 2 in the stack

Stack.pop() # removing the top element (2)

Stack.pop() # removing the top element (1)

Stack.push(3) # Inserting 3 in the stack

Print(“Top element is”, stack.peek())

Print(“The stack size is”, stack.size())

Stack.pop() # removing the top element (3)

# check if the stack is empty

If stack.isEmpty():

Print(“The stack is empty”)

Else:

Print(“The stack is not empty”)

OUTPUT:

Inserting 1 into the stack…

Inserting 2 into the stack…

Removing 2 from the stack

Removing 1 from the stack

Inserting 3 into the stack…

Top element is 3

The stack size is 1

Removing 3 from the stack

The stack is empty

RESULT:

Thus,the program for implement sack in Python has been executed successfully.
QUEUE

AIM:

To write a python program to implement queue.


ALGORITHM:
Step 1:Start the program.
Step 2:Create a Queue and initialize front and rear positions as first and last indices of queue list.
Step 3:Define pop function,delete the element and modify the position of front and decrement count.
Step 4:Define append function,add the element to the queue if queue is not full,modify the position of
rear and increment count.
Step 5:Define peek function,and get the position of front value
Step 6:Define size function and return count of the elements in the queue.
Step 7:Define functions to check if the queue is full or empty by returning the size.
Step 8:Add elements and pop out some elements.
Step 9:If queue is empty,display the same,else,display the queue.
Step 10:Stop the program.
PROGRAM:
# Custom queue implementation in Python
Class Queue:
# Initialize queue
Def __init__(self, size):
Self.q = [None] * size # list to store queue elements
Self.capacity = size # maximum capacity of the queue
Self.front = 0 # front points to the front element in the queue
Self.rear = -1 # rear points to the last element in the queue
Self.count = 0 # current size of the queue
# Function to dequeue the front element
Def pop(self):
# check for queue underflow
If self.isEmpty():
Print(“Queue Underflow!! Terminating process.”)
Exit(1)
Print(“Removing element…”, self.q[self.front])
Self.front = (self.front + 1) % self.capacity
Self.count = self.count – 1
# Function to add an element to the queue
Def append(self, value):
# check for queue overflow
If self.isFull():
Print(“Overflow!! Terminating process.”)
Exit(1)
Print(“Inserting element…”, value)
Self.rear = (self.rear + 1) % self.capacity
Self.q[self.rear] = value
Self.count = self.count + 1
# Function to return the front element of the queue
Def peek(self):
If self.isEmpty():
Print(“Queue UnderFlow!! Terminating process.”)
Exit(1)
Return self.q[self.front]
# Function to return the size of the queue
Def size(self):
Return self.count
# Function to check if the queue is empty or not
Def isEmpty(self):
Return self.size() == 0
# Function to check if the queue is full or not
Def isFull(self):
Return self.size() == self.capacity
If __name__ == ‘__main__’:
# create a queue of capacity 5
Q = Queue(5)
q.append(1)
q.append(2)
q.append(3)
print(“The queue size is”, q.size())
print(“The front element is”, q.peek())
q.pop()
print(“The front element is”, q.peek())
q.pop()
q.pop()
if q.isEmpty():
print(“The queue is empty”)
else:
print(“The queue is not empty”)
OUTPUT:
Inserting element… 1
Inserting element… 2
Inserting element… 3
The queue size is 3
The front element is 1
Removing element… 1
The front element is 2
Removing element… 2
Removing element… 3
The queue is empty

RESULT:

Thus,the program for implement queue in Python has been executed successfully.
6. APPLICATIONS OF LIST, STACK AND QUEUE ADTs

POLYNOMIAL LIST
AIM:
To write a python program to implement polynomial list.

ALGORITHM:
Step 1:Start the program.
Step 2:Declare the list of coefficients and define the value of x.
Step 3:Run a loop to traverse through the list.
Step 4:Declare sum.
Step 5:Run a loop to multiply the coefficient to the powers of x.
Step 6:Compute the sum and display the sum.
Step 7:Stop the program.
Step 7:If the priority of operator in stack is less than the next element,pop out the element in stack.
Step 8:Call the function and display the all the other elements.
Step 9:Display the post fix expression.
Step 10:Stop the program.
PROGRAM:

Poly = [2, -6, 2, -1]

X=3

N = len(poly)

# Declaring the result

Result = 0

# Running a for loop to traverse through the list

For I in range(n):

# Declaring the variable Sum

Sum = poly[i]
# Running a for loop to multiply x (n-i-1)

# times to the current coefficient

For j in range(n – I – 1):

Sum = Sum * x

# Adding the sum to the result

Result = result + Sum

# Printing the result

Print(result)

OUTPUT:

Result:5

INVERSION OF INFIX TO POSTFIX(STACK)


AIM:
To write a python program to implement inversion of infix to postfix.

ALGORITHM:
Step 1:Start the program.

Step 2:Declare the operators and priorities for the operator.

Step 3:Using loop traverse the expression.

Step 4:Define function infixtopostfix,if the operator not in operator list,append in the stack.

Step 5:If found a open bracket,append the open bracket.

Step 6:Pop out all the elements till the close bracket is reached.

Step 7:If the priority of operator in stack is less than the next element,pop out the element in stack.

Step 8:Call the function and display the all the other elements.

Step 9:Display the post fix expression.

Step 10:Stop the program.

PROGRAM:

Operators = set([‘+’, ‘-‘, ‘*’, ‘/’, ‘(‘, ‘)’, ‘^’]) # collection of Operators

Priority = {‘+’:1, ‘-‘:1, ‘*’:2, ‘/’:2, ‘^’:3} # dictionary having priorities of Operators
Def infixToPostfix(expression):

Stack = [] # initialization of empty stack

Output = ‘’

For character in expression:

If character not in Operators: # if an operand append in postfix expression

Output+= character

Elif character==’(‘: # else Operators push onto stack

Stack.append(‘(‘)

Elif character==’)’:

While stack and stack[-1]!= ‘(‘:

Output+=stack.pop()

Stack.pop()

Else:

While stack and stack[-1]!=’(‘ and Priority[character]<=Priority[stack[-1]]:

Output+=stack.pop()

Stack.append(character)

While stack:

Output+=stack.pop()

Return output

Expression = input(‘Enter infix expression ‘)

Print(‘infix notation: ‘,expression)

Print(‘postfix notation: ‘,infixToPostfix(expression))

OUTPUT:
PRIORITY QUEUE
AIM:
To write a python program to implement priority queue.

ALGORITHM:
Step 1:Start the program.
Step 2:Declare queue as list.
Step 3:Define functions to check if the list is empty and to add elements.
Step 4:Delete the particular element which is prioritized.
Step 5:Display the queue.
Step 6:Stop the program.
PROGRAM:

Class PriorityQueue(object):

Def __init__(self):

Self.queue = []

Def __str__(self):

Return ‘ ‘.join([str(i) for I in self.queue])

# for checking if the queue is empty

Def isEmpty(self):

Return len(self.queue) == 0

# for inserting an element in the queue

Def insert(self, data):

Self.queue.append(data)

# for popping an element based on Priority

Def delete(self):

Try:

Max_val = 0

For I in range(len(self.queue)):

If self.queue[i] > self.queue[max_val]:

Max_val = i
Item = self.queue[max_val]

Del self.queue[max_val]

Return item

Except IndexError:

Print()

Exit()

If __name__ == ‘__main__’:

myQueue = PriorityQueue()

myQueue.insert(12)

myQueue.insert(1)

myQueue.insert(14)

myQueue.insert(7)

print(myQueue)

while not myQueue.isEmpty():

print(myQueue.delete())

OUTPUT:

RESULT:

Thus, the program for application of list, stack and queue ADTs in python has been executed
successful.
7. IMPLEMENTATION OF SORTING AND SEARCHING ALGORITHMS

SEARCHING:

A.LINEAR SEARCH

AIM:

To write a python program to perform linear search.

ALGORITHM:

Step 1:Start the program

Step 2:Read the search item, “item.”

Step 3:Initiate i=0 and index=-1

Step 4:If i<N, go to step 4. Else, go to step 8.

Step 5:If Data[i] equals to “item,” then go to step 5. Else go to step 6.

Step 6:Index = I (As the item is found at index no i). Go to step 8.

Step 7:I = I +1.

Step 8:Go to step 3.

Step 9:Stop the program

PROGRAM:

Def linearSearch(target, List):

Position = 0

Global iterations

Iterations = 0

While position < len(List):

Iterations += 1

If target == List[position]:

Return position

Position += 1
Return -1

If __name__ == ‘__main__’:

List = [1, 2, 3, 4, 5, 6, 7, 8]

Target = 3

Answer = linearSearch(target, List)

If answer != -1:

Print(‘Target found at index :’, answer, ‘in’,

Iterations,’iterations’)

Else:

Print(‘Target not found in the list’)

OUTPUT:

Target found at index : 2 in 3 iterations

B.BINARY SEARCH

AIM:

To write a python program to perform binary search.

ALGORITHM:

Step 1:Start the program.

Step 2:Compare x with the middle element.

Step 3:If x matches with the middle element, we return the mid index.

Step 4:Else if x is greater than the mid element, then x can only lie in the right (greater) half subarray
after the mid element. Then we apply the algorithm again for the right half.

Step 5:Else if x is smaller, the target x must lie in the left (lower) half. So we apply the algorithm for the
left half.

Step 6:Stop the program.

PROGRAM:

def binarySearch(target, List):


left = 0
right = len(List) - 1
global iterations
iterations = 0
while left <= right:
iterations += 1
mid = (left + right) // 2
if target == List[mid]:
return mid
elif target < List[mid]:
right = mid - 1
else:
left = mid + 1
return -1
if __name__ == '__main__':
List = [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 14]
target = 12
answer = binarySearch(target, List)
if(answer != -1):
print('Target',target,'found at position', answer, 'in',
iterations,'iterations')
else:
print('Target not found')

OUTPUT:
Target 12 found at position 10 in 4 iterations
SORTING:

A.BUBBLE SORT

AIM:

To write a python program to perform bubble sort.

ALGORITHM:

Step 1:Start the program.

Step 2:Get the total number of elements. Get the total number of items in the given list.

Step 3:Determine the number of outer passes (n – 1) to be done. Its length is list minus one.

Step 4:Perform inner passes (n – 1) times for outer pass 1. Get the first element value and compare it
with the second value. If the second value is less than the first value, then swap the positions.

Step 5:Repeat step 3 passes until you reach the outer pass (n – 1). Get the next element in the list then
repeat the process that was performed in step 3 until all the values have been placed in their correct
ascending order.

Step 6:Return the result when all passes have been done. Return the results of the sorted list.

Step 7:Optimize Algorithm.

Step 8:Stop the program.

PROGRAM:

Def bubble_sort(alist):

For I in range(len(alist) – 1, 0, -1):

No_swap = True

For j in range(0, i):

If alist[j + 1] < alist[j]:

Alist[j], alist[j + 1] = alist[j + 1], alist[j]

No_swap = False

If no_swap:

Return

Alist = input(‘Enter the list of numbers: ‘).split()

Alist = [int(x) for x in alist]

Bubble_sort(alist)

Print(‘Sorted list: ‘, alist)


OUTPUT:

Enter the list of numbers: 23 45 3 2 6

Sorted list: [2, 3, 6, 23, 45]

B. SELECTION SORT

AIM:

To write a python program to perform selection sort.

ALGORITHM:

Step 1:Start the program.

Step 2:Get the value of n which is the total size of the array.

Step 3:Partition the list into sorted and unsorted sections. The sorted section is initially empty while the
unsorted section contains the entire list.

Step 4:Pick the minimum value from the unpartitioned section and placed it into the sorted section.

Step 5:Repeat the process (n – 1) times until all of the elements in the list have been sorted.

Step 6:Stop the program.

PROGRAM:

Def selection_sort(alist):

For I in range(0, len(alist) – 1):

Smallest = i

For j in range(I + 1, len(alist)):

If alist[j] < alist[smallest]:

Smallest = j

Alist[i], alist[smallest] = alist[smallest], alist[i]

Alist = input(‘Enter the list of numbers: ‘).split()

Alist = [int(x) for x in alist]

Selection_sort(alist)

Print(‘Sorted list: ‘, alist)


OUTPUT:

Enter the list of numbers: 45 23 6 8 1 3

Sorted list: [1, 3, 6, 8, 23, 45]

C. MERGE SORT

AIM:
To write a python program to perform merge sort.

ALGORITHM:
Step 1:Start the program.
Step 2:Divide the arrays into subarray.
Step 3:Use recursion function to divide and conquer subarrays.
Step 4:Sort the subarrays using recursive function.
Step 5:If the size of the subarrays are not equal add the remaining element to the sorted array in correct
position.
Step 6:Combine the subarrays together.
Step 7:Stop the program.
PROGRAM:
Def merge_sort(alist, start, end):
‘’’Sorts the list from indexes start to end – 1 inclusive.’’’
If end – start > 1:
Mid = (start + end)//2
Merge_sort(alist, start, mid)
Merge_sort(alist, mid, end)
Merge_list(alist, start, mid, end)
Def merge_list(alist, start, mid, end):
Left = alist[start:mid]
Right = alist[mid:end]
K = start
I=0
J=0
While (start + I < mid and mid + j < end):
If (left[i] <= right[j]):
Alist[k] = left[i]
I=I+1
Else:
Alist[k] = right[j]
J=j+1
K=k+1
If start + I < mid:
While k < end:
Alist[k] = left[i]
I=I+1
K=k+1
Else:
While k < end:
Alist[k] = right[j]
J=j+1
K=k+1
Alist = input(‘Enter the list of numbers: ‘).split()
Alist = [int(x) for x in alist]
Merge_sort(alist, 0, len(alist))
Print(‘Sorted list: ‘, alist)

OUTPUT::
Enter the list of numbers: 12 3 4 1 67 0
Sorted list: [0, 1, 3, 4, 12, 67]
D.QUICK SORT

AIM:

To write a python program to perform quick sort.

ALGORITHM:

Step 1:Start the program.

Step 2:Divide the array into subarrays by choosing a pivot element.

Step 3:The elements on the left side are lesser than pivot element whereas the elements on the right
side are greater than pivot element.

Step 4:This process is continued till the sub arrays contain single element.

Step 5:Elements are sorted.

Step 6:Combine the subarrays.

Step 7:Stop the program.

PROGRAM:.

Def quicksort(alist, start, end):

‘’’Sorts the list from indexes start to end – 1 inclusive.’’’

If end – start > 1:

P = partition(alist, start, end)

Quicksort(alist, start, p)

Quicksort(alist, p + 1, end)

Def partition(alist, start, end):

Pivot = alist[start]

I = start + 1

J = end – 1

While True:

While (I <= j and alist[i] <= pivot):

I=I+1

While (I <= j and alist[j] >= pivot):

J=j–1
If I <= j:

Alist[i], alist[j] = alist[j], alist[i]

Else:

Alist[start], alist[j] = alist[j], alist[start]

Return j

Alist = input(‘Enter the list of numbers: ‘).split()

Alist = [int(x) for x in alist]

Quicksort(alist, 0, len(alist))

Print(‘Sorted list: ‘, alist)

OUTPUT:

Enter the list of numbers: 12 3 56 7 1 9

Sorted list: [1, 3, 7, 9, 12, 56]

RESULT:

Thus, the program for implementing sorting and searching algorithms in Python has been excited
successful.
8. IMPLEMENTATION OF HASH TABLE

AIM:

To write a python program of implementating hash table.

ALGORITHM:

Step 1:Start the process.

Step 2:Create an empty hash table.

Step 3:Insert a key-value pair to the hash table.

Step 4:Delete a key-value pair from a hash table.

Step 5:Find a value by key in the table.

Step 6:Update the value associated with an existing key.

Step 7:Check if the hash table has a given key.

Step 8:Return a default value if the corresponding key is not found.

Step 9:End the program.

PROGRAM:

Def display_hash(hashTable):

For I in range(len(hashTable)):

Print(I, end = “ “)

For j in hashTable[i]:

Print(“”, end = “ “)

Print(j, end = “ “)

Print()

# Creating Hashtable as

# a nested list.

HashTable = [[] for _ in range(10)]

# Hashing Function to return

# key for every value.

Def Hashing(keyvalue):
Return keyvalue % len(HashTable)

# Insert Function to add

# values to the hash table

Def insert(Hashtable, keyvalue, value):

Hash_key = Hashing(keyvalue)

Hashtable[hash_key].append(value)

# Driver Code

Insert(HashTable, 10, ‘Allahabad’)

Insert(HashTable, 25, ‘Mumbai’)

Insert(HashTable, 20, ‘Mathura’)

Insert(HashTable, 9, ‘Delhi’)

Insert(HashTable, 21, ‘Punjab’)

Insert(HashTable, 21, ‘Noida’)

Display_hash (HashTable)

OUTPUT:

0  Allahabad  Mathura

1  Punjab  Noida

5  Mumbai

9  Delhi

RESULT:

Thus,the program for implementation of hash table in Python has been executed successfully.
9. TREE REPRESENTATION AND TRAVERSAL ALGORITHMS

AIM:
To write a python program to implement tree representation and traversal algorithms.

ALGORITHM:
Step 1:Start the program.
Step 2:Creating a class as node.
Step 3:Define print Inorder.
Step 4:Define print Postorder.
Step 5:Define print Preorder.
Step 6:Print preoder traversal of binary tree.
Step 7:Print inorder traversal of binary tree.
Step 8:Print postoder traversal of binary tree.
Step 9:Stop the program.
PROGRAM:

Class Node:

Def __init__(self, data):

Self.left = None

Self.right = None

Self.data = data

# Insert Node

Def insert(self, data):

If self.data:

If data < self.data:

If self.left is None:

Self.left = Node(data)

Else:
Self.left.insert(data)

Else:

Data > self.data

If self.right is None:

Self.right = Node(data)

Else:

Self.right.insert(data)

Else:

Self.data = data

# Print the Tree

Def PrintTree(self):

If self.left:

Self.left.PrintTree()

Print( self.data),

If self.right:

Self.right.PrintTree()

# Inorder traversal

# Left -> Root -> Right

Def inorderTraversal(self, root):

Res = []

If root:

Res = self.inorderTraversal(root.left)

Res.append(root.data)

Res = res + self.inorderTraversal(root.right)

Return res

Def PreorderTraversal(self, root):

Res = []

If root:

Res.append(root.data)
Res = res + self.PreorderTraversal(root.left)

Res = res + self.PreorderTraversal(root.right)

Return res

# Postorder traversal

# Left ->Right -> Root

Def PostorderTraversal(self, root):

Res = []

If root:

Res = self.PostorderTraversal(root.left)

Res = res + self.PostorderTraversal(root.right)

Res.append(root.data)

Return res

Root = Node(27)

Root.insert(14)

Root.insert(35)

Root.insert(10)

Root.insert(19)

Root.insert(31)

Root.insert(42)

Print(root.inorderTraversal(root))

Print(root.PreorderTraversal(root))

Print(root.PostorderTraversal(root))

OUTPUT:

[10, 14, 19, 27, 31, 35, 42]

[27, 14, 10, 19, 35, 31, 42]

[10, 19, 14, 31, 42, 35, 27]

RESULT:
Thus,the program for implementing tree representation and traversal algorithms in Python has been
executed successfully.

10. IMPLEMENTATION OF BINARY SEARCH TREE

AIM:

To write a python program for implementation of Binary Search Tree.

ALGORITHM:

Step 1: Start the process.

Step 2: Creating a class as node.

Step 3: Define insert function.

Step 4: Define replace node of parent.

Step 5: Define remove function.

Step 6: Define search function.

Step 7: Stop the process.

PROGRAM:

Class Node:

Def __init__(self, data):

Self.left = None

Self.right = None

Self.data = data

# Insert method to create nodes

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

# findval method to compare the value with nodes

Def findval(self, lkpval):

If lkpval < self.data:

If self.left is None:

Return str(lkpval)+” is not Found”

Return self.left.findval(lkpval)

Elif lkpval > self.data:

If self.right is None:

Return str(lkpval)+” is not Found”

Return self.right.findval(lkpval)

Else:

Return str(self.data) + “ is found”

# Print the tree

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)

Print(root.findval(7))

Print(root.findval(14))

OUTPUT:

7 is not Found

14 is found

RESULT:

Thus,the program for implementation of binary search tree in Python has been executed successfully.
11. IMPLEMENTATION OF HEAPS

AIM:

To write a python program for implementation of Heaps.

ALGORITHM:

Step 1:Start the program.

Step 2:Import heapq library.

Step 3:Create a list with elements and then heapify.

Step 4:Print the created heap.

Step 5:Push the element 4 with the help of heappush.

Step 6:Print the modified heap after push.

Step 7:Pop the smallest element from the list with the help of heappop.

Step 8:Print the popped and smallest element.

Step 9:Stop the program.

PROGRAM:

Min Heap:

# Python3 implementation of Min Heap

Import sys

Class MinHeap:

Def __init__(self, maxsize):

Self.maxsize = maxsize

Self.size = 0

Self.Heap = [0]*(self.maxsize + 1)

Self.Heap[0] = -1 * sys.maxsize

Self.FRONT = 1

# Function to return the position of

# parent for the node currently


# at pos

Def parent(self, pos):

Return pos//2

# Function to return the position of

# the left child for the node currently

# at pos

Def leftChild(self, pos):

Return 2 * pos

# Function to return the position of

# the right child for the node currently

# at pos

Def rightChild(self, pos):

Return (2 * pos) + 1

# Function that returns true if the passed

# node is a leaf node

Def isLeaf(self, pos):

Return pos*2 > self.size

# Function to swap two nodes of the heap

Def swap(self, fpos, spos):

Self.Heap[fpos], self.Heap[spos] = self.Heap[spos], self.Heap[fpos]

# Function to heapify the node at pos

Def minHeapify(self, pos):

# If the node is a non-leaf node and greater

# than any of its child

If not self.isLeaf(pos):

If (self.Heap[pos] > self.Heap[self.leftChild(pos)] or

Self.Heap[pos] > self.Heap[self.rightChild(pos)]):

# Swap with the left child and heapify

# the left child


If self.Heap[self.leftChild(pos)] < self.Heap[self.rightChild(pos)]:

Self.swap(pos, self.leftChild(pos))

Self.minHeapify(self.leftChild(pos))

# Swap with the right child and heapify

# the right child

Else:

Self.swap(pos, self.rightChild(pos))

Self.minHeapify(self.rightChild(pos))

# Function to insert a node into the heap

Def insert(self, element):

If self.size >= self.maxsize :

Return

Self.size+= 1

Self.Heap[self.size] = element

Current = self.size

While self.Heap[current] < self.Heap[self.parent(current)]:

Self.swap(current, self.parent(current))

Current = self.parent(current)

# Function to print the contents of the heap

Def Print(self):

For I in range(1, (self.size//2)+1):

Print(“ PARENT : “+ str(self.Heap[i])+” LEFT CHILD : “+

Str(self.Heap[2 * i])+” RIGHT CHILD : “+

Str(self.Heap[2 * I + 1]))

# Function to build the min heap using

# the minHeapify function

Def minHeap(self):

For pos in range(self.size//2, 0, -1):

Self.minHeapify(pos)
# Function to remove and return the minimum

# element from the heap

Def remove(self):

Popped = selfheap[self.FRONT]

Self.Heap[self.FRONT] = self.Heap[self.size]

Self.size-= 1

Self.minHeapify(self.FRONT)

Return popped

# Driver Code

If __name__ == “__main__”:

Print(‘The minHeap is ‘)

minHeap = MinHeap(15)

minHeap.insert(5)

minHeap.insert(3)

minHeap.insert(17)

minHeap.insert(10)

minHeap.insert(84)

minHeap.insert(19)

minHeap.insert(6)

minHeap.insert(22)

minHeap.insert(9)

minHeap.minHeap()

minHeap.Print()

print(“The Min val is “ + str(minHeap.remove()))

OUTPUT:

The minHeap is

PARENT : 3 LEFT CHILD : 5 RIGHT CHILD : 6


PARENT : 5 LEFT CHILD : 9 RIGHT CHILD : 84

PARENT : 6 LEFT CHILD : 19 RIGHT CHILD : 17

PARENT : 9 LEFT CHILD : 22 RIGHT CHILD : 10

The Min val is 3

Max Heap:

# Python3 implementation of Max Heap

Import sys

Class MaxHeap:

Def __init__(self, maxsize):

Self.maxsize = maxsize

Self.size = 0

Self.Heap = [0] * (self.maxsize + 1)

Self.Heap[0] = sys.maxsize

Self.FRONT = 1

# Function to return the position of

# parent for the node currently

# at pos

Def parent(self, pos):

Return pos // 2

# Function to return the position of

# the left child for the node currently

# at pos

Def leftChild(self, pos):

Return 2 * pos

# Function to return the position of

# the right child for the node currently

# at pos

Def rightChild(self, pos):


Return (2 * pos) + 1

# Function that returns true if the passed

# node is a leaf node

Def isLeaf(self, pos):

If pos >= (self.size//2) and pos <= self.size:

Return True

Return False

# Function to swap two nodes of the heap

Def swap(self, fpos, spos):

Self.Heap[fpos], self.Heap[spos] = (self.Heap[spos],

Self.Heap[fpos])

# Function to heapify the node at pos

Def maxHeapify(self, pos):

# If the node is a non-leaf node and smaller

# than any of its child

If not self.isLeaf(pos):

If (self.Heap[pos] < self.Heap[self.leftChild(pos)] or

Self.Heap[pos] < self.Heap[self.rightChild(pos)]):

# Swap with the left child and heapify

# the left child

If (self.Heap[self.leftChild(pos)] >

Self.Heap[self.rightChild(pos)]):

Self.swap(pos, self.leftChild(pos))

Self.maxHeapify(self.leftChild(pos))

# Swap with the right child and heapify

# the right child

Else:

Self.swap(pos, self.rightChild(pos))

Self.maxHeapify(self.rightChild(pos))
# Function to insert a node into the heap

Def insert(self, element):

If self.size >= self.maxsize:

Return

Self.size += 1

Self.Heap[self.size] = element

Current = self.size

While (self.Heap[current] >

Self.Heap[self.parent(current)]):

Self.swap(current, self.parent(current))

Current = self.parent(current)

# Function to print the contents of the heap

Def Print(self):

For I in range(1, (self.size // 2) + 1):

Print(“PARENT : “ + str(self.Heap[i]) +

“LEFT CHILD : “ + str(self.Heap[2 * i]) +

“RIGHT CHILD : “ + str(self.Heap[2 * I + 1]))

# Function to remove and return the maximum

# element from the heap

Def extractMax(self):

Popped = self.Heap[self.FRONT]

Self.Heap[self.FRONT] = self.Heap[self.size]

Self.size -= 1

Self.maxHeapify(self.FRONT)

Return popped

# Driver Code

If __name__ == “__main__”:

Print(‘The maxHeap is ‘)
maxHeap = MaxHeap(15)

maxHeap.insert(5)

maxHeap.insert(3)

maxHeap.insert(17)

maxHeap.insert(10)

maxHeap.insert(84)

maxHeap.insert(19)

maxHeap.insert(6)

maxHeap.insert(22)

maxHeap.insert(9)

maxHeap.Print()

print(“The Max val is “ + str(maxHeap.extractMax()))

OUTPUT:

The maxHeap is

PARENT : 84LEFT CHILD : 22RIGHT CHILD : 19

PARENT : 22LEFT CHILD : 17RIGHT CHILD : 10

PARENT : 19LEFT CHILD : 5RIGHT CHILD : 6

PARENT : 17LEFT CHILD : 3RIGHT CHILD : 9

The Max val is 84

RESULT:

Thus,the program for implementation of heaps in Python has been executed successfully.
12. GRAPH REPRESENTATION AND TRAVERSAL ALGORITHMS

AIM:

To write a python program to implement the graph representation and traversal algorithms.

ALGORITHM:

Step 1:Start the program.

Step 2:Import default dict.

Step 3:Creating a graph with default dict(list)

Step 4:Define addEdge.

Step 5:Define generate_edges.

Step 6:Create a edge with a empty list.

Step 7:For node in graph.

For neighbour in graph[node].

Step 8:Append the edge.

Step 9:Print the generated graph.

Step 10:Stop the program.

PROGRAM:

Breadth-First Traversal of a tree

# Python3 Program to print BFS traversal

# from a given source vertex. BFS(int s)

# traverses vertices reachable from s.

From collections import defaultdict

# This class represents a directed graph

# using adjacency list representation

Class Graph:

# Constructor

Def __init__(self):
# default dictionary to store graph

Self.graph = defaultdict(list)

# function to add an edge to graph

Def addEdge(self,u,v):

Self.graph[u].append(v)

# Function to print a BFS of graph

Def BFS(self, s):

# Mark all the vertices as not visited

Visited = [False] * (max(self.graph) + 1)

# Create a queue for BFS

Queue = []

# Mark the source node as

# visited and enqueue it

Queue.append(s)

Visited[s] = True

While queue:

# Dequeue a vertex from

# queue and print it

S = queue.pop(0)

Print (s, end = “ “)

# Get all adjacent vertices of the

# dequeued vertex s. If a adjacent

# has not been visited, then mark it

# visited and enqueue it

For I in self.graph[s]:

If visited[i] == False:

Queue.append(i)

Visited[i] = True

# Driver code
# Create a graph given in

# the above diagram

G = Graph()

g.addEdge(0, 1)

g.addEdge(0, 2)

g.addEdge(1, 2)

g.addEdge(2, 0)

g.addEdge(2, 3)

g.addEdge(3, 3)

print (“Following is Breadth First Traversal”

“ (starting from vertex 2)”)

g.BFS(2)

OUTPUT:

Following is Breadth First Traversal (starting from vertex 2)

2031

Depth First Traversal of a tree.

# Python3 program to print DFS traversal

# from a given graph

From collections import defaultdict

# This class represents a directed graph using

# adjacency list representation

Class Graph:

# Constructor

Def __init__(self):

# default dictionary to store graph

Self.graph = defaultdict(list)

# function to add an edge to graph


Def addEdge(self, u, v):

Self.graph[u].append(v)

# A function used by DFS

Def DFSUtil(self, v, visited):

# Mark the current node as visited

# and print it

Visited.add(v)

Print(v, end=’ ‘)

# Recur for all the vertices

# adjacent to this vertex

For neighbour in self.graph[v]:

If neighbour not in visited:

Self.DFSUtil(neighbour, visited)

# The function to do DFS traversal. It uses

# recursive DFSUtil()

Def DFS(self, v):

# Create a set to store visited vertices

Visited = set()

# Call the recursive helper function

# to print DFS traversal

Self.DFSUtil(v, visited)

# Driver’s code

# Create a graph given

# in the above diagram

If __name__ == “__main__”:

G = Graph()

g.addEdge(0, 1)

g.addEdge(0, 2)

g.addEdge(1, 2)
g.addEdge(2, 0)

g.addEdge(2, 3)

g.addEdge(3, 3)

print(“Following is DFS from (starting from vertex 2)”)

# Function call

g.DFS(2)

OUTPUT:

Following is DFS from (starting from vertex 2)

2013

RESULT:

Thus,the program for implementing graph representation and traversal algorithm in Python has been
executed successfully.
13. IMPLEMENTATION OF SINGLE SOURCE SHORTEST PATH ALGORITHM

AIM:

To write a python program to implement the shortest path algorithm.

ALGORITHM:
Step 1:Start the process.
Step 2:Creating a class graph.
Step 3:Define print solution.
Step 4:Print vertex distance from source.
Step 5:Define min distance.
Step 6:Define dijkstra.
Step 7:Creating an object for the class graph.
Step 8:Print the shortest path.
Step 9:Stop the process.
PROGRAM:
Class Graph():

Def __init__(self, vertices):

Self.V = vertices

Self.graph = [[0 for column in range(vertices)]

For row in range(vertices)]

Def printSolution(self, dist):

Print(“Vertex \t Distance from Source”)

For node in range(self.V):

Print(node, “\t\t”, dist[node])

# A utility function to find the vertex with

# minimum distance value, from the set of vertices

# not yet included in shortest path tree

Def minDistance(self, dist, sptSet):


# Initialize minimum distance for next node

Min = 1e7

# Search not nearest vertex not in the

# shortest path tree

For v in range(self.V):

If dist[v] < min and sptSet[v] == False:

Min = dist[v]

Min_index = v

Return min_index

# Function that implements Dijkstra’s single source

# shortest path algorithm for a graph represented

# using adjacency matrix representation

Def dijkstra(self, src):

Dist = [1e7] * self.V

Dist[src] = 0

sptSet = [False] * self.V

for cout in range(self.V):

# Pick the minimum distance vertex from

# the set of vertices not yet processed.

# u is always equal to src in first iteration

U = self.minDistance(dist, sptSet)

# Put the minimum distance vertex in the

# shortest path tree

sptSet[u] = True

# Update dist value of the adjacent vertices

# of the picked vertex only if the current

# distance is greater than new distance and

# the vertex in not in the shortest path tree

For v in range(self.V):
If (self.graph[u][v] > 0 and

sptSet[v] == False and

dist[v] > dist[u] + self.graph[u][v]):

dist[v] = dist[u] + self.graph[u][v]

self.printSolution(dist)

# Driver program

G = Graph(9)

g.graph = [[0, 4, 0, 0, 0, 0, 0, 8, 0],

[4, 0, 8, 0, 0, 0, 0, 11, 0],

[0, 8, 0, 7, 0, 4, 0, 0, 2],

[0, 0, 7, 0, 9, 14, 0, 0, 0],

[0, 0, 0, 9, 0, 10, 0, 0, 0],

[0, 0, 4, 14, 10, 0, 2, 0, 0],

[0, 0, 0, 0, 0, 2, 0, 1, 6],

[8, 11, 0, 0, 0, 0, 1, 0, 7],

[0, 0, 2, 0, 0, 0, 6, 7, 0]

g.dijkstra(0)

OUTPUT:

Vertex Distance from Source

0 0
1 1 4
2 12
3 3 19
4 21
5 5 11
6 9
7 7 8
8 14
9
RESULT:

Thus,the program for implementing the single source shortest path algorithm in Python has been
executed successfully.
14. IMPLEMENTATION OF MINIMUM SPANNING TREE ALGORITHMS

AIM:

To write a python program to implement the minimum spanning tree algorithm.

ALGORITHM:

Step 1:Start the process.

Step 2:Import default dict.

Step 3:Creating a class graph.

Step 4:Define add edge.

Step 5:Define find function.

Step 6:Define union function.

Step 7:Define KruskalMST.

Step 8:Print the edges in the Constructed MST.

Step 9:Creating an object for the class graph.

Step 10:Print the minimum spanning tree.

Step 11:Stop the process.

PROGRAM:

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


# A utility function to find the vertex with

# minimum distance value, from the set of vertices

# not yet included in shortest path tree

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

# Function to construct and print MST for a graph

# represented using adjacency matrix representation

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 # First node is always the root of

for cout in range(self.V):

# Pick the minimum distance vertex from

# the set of vertices not yet processed.

# u is always equal to src in first iteration

U = self.minKey(key, mstSet)

# Put the minimum distance vertex in

# the shortest path tree

mstSet[u] = True
# Update dist value of the adjacent vertices

# of the picked vertex only if the current

# distance is greater than new distance and

# the vertex in not in the shortest path tree

For v in range(self.V):

# graph[u][v] is non zero only for adjacent vertices of m

# mstSet[v] is false for vertices not yet included in MST

# Update the key only if graph[u][v] is smaller than key[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 program for implementing the minimum spanning tree algorithm in Python has been
executed successfully.

15. RED BLACK TREE

AIM:

To write a python program to implement the red and black tree structure.

ALGORITHM:

1.Start the program

2.Creating the node

3.Traverse the tree using inorder,postorder,preorder

4.Search the tree and delete the node

5.Transplant the node

6.Delete the node and balance the tree after deletion

7.Displaying the tree

8.Call the function to traverse and rotate the tree structure to balance

9.Stop the program

PROGRAM:

Import sys

# Node creation

Class Node():

Def __init__(self, item):

Self.item = item

Self.parent = None

Self.left = None

Self.right = None

Self.color = 1

Class RedBlackTree():
Def __init__(self):

Self.TNULL = Node(0)

Self.TNULL.color = 0

Self.TNULL.left = None

Self.TNULL.right = None

Self.root = self.TNULL

# Preorder

Def pre_order_helper(self, node):

If node != TNULL:

Sys.stdout.write(node.item + “ “)

Self.pre_order_helper(node.left)

Self.pre_order_helper(node.right)

# Inorder

Def in_order_helper(self, node):

If node != TNULL:

Self.in_order_helper(node.left)

Sys.stdout.write(node.item + “ “)

Self.in_order_helper(node.right)

# Postorder

Def post_order_helper(self, node):

If node != TNULL:

Self.post_order_helper(node.left)

Self.post_order_helper(node.right)

Sys.stdout.write(node.item + “ “)

# Search the tree

Def search_tree_helper(self, node, key):

If node == TNULL or key == node.item:

Return node

If key < node.item:


Return self.search_tree_helper(node.left, key)

Return self.search_tree_helper(node.right, key)

# Balancing the tree after deletion

Def delete_fix(self, x):

While x != self.root and x.color == 0:

If x == x.parent.left:

S = x.parent.right

If s.color == 1:

s.color = 0

x.parent.color = 1

self.left_rotate(x.parent)

s = x.parent.right

if s.left.color == 0 and s.right.color == 0:

s.color = 1

x = x.parent

else:

if s.right.color == 0:

s.left.color = 0

s.color = 1

self.right_rotate(s)

s = x.parent.right

s.color = x.parent.color

x.parent.color = 0

s.right.color = 0

self.left_rotate(x.parent)

x = self.root

else:

s = x.parent.left
if s.color == 1:

s.color = 0

x.parent.color = 1

self.right_rotate(x.parent)

s = x.parent.left

if s.right.color == 0 and s.right.color == 0:

s.color = 1

x = x.parent

else:

if s.left.color == 0:

s.right.color = 0

s.color = 1

self.left_rotate(s)

s = x.parent.left

s.color = x.parent.color

x.parent.color = 0

s.left.color = 0

self.right_rotate(x.parent)

x = self.root

x.color = 0

def __rb_transplant(self, u, v):

if u.parent == None:

self.root = v

elif u == u.parent.left:

u.parent.left = v

else:

u.parent.right = v

v.parent = u.parent

# Node deletion
Def delete_node_helper(self, node, key):

Z = self.TNULL

While node != self.TNULL:

If node.item == key:

Z = node

If node.item <= key:

Node = node.right

Else:

Node = node.left

If z == self.TNULL:

Print(“Cannot find key in the tree”)

Return

Y=z

Y_original_color = y.color

If z.left == self.TNULL:

X = z.right

Self.__rb_transplant(z, z.right)

Elif (z.right == self.TNULL):

X = z.left

Self.__rb_transplant(z, z.left)

Else:

Y = self.minimum(z.right)

Y_original_color = y.color

X = y.right

If y.parent == z:

x.parent = y

else:

self.__rb_transplant(y, y.right)

y.right = z.right
y.right.parent = y

self.__rb_transplant(z, y)

y.left = z.left

y.left.parent = y

y.color = z.color

if y_original_color == 0:

self.delete_fix(x)

# Balance the tree after insertion

Def fix_insert(self, k):

While k.parent.color == 1:

If k.parent == k.parent.parent.right:

U = k.parent.parent.left

If u.color == 1:

u.color = 0

k.parent.color = 0

k.parent.parent.color = 1

k = k.parent.parent

else:

if k == k.parent.left:

k = k.parent

self.right_rotate(k)

k.parent.color = 0

k.parent.parent.color = 1

self.left_rotate(k.parent.parent)

else:

u = k.parent.parent.right

if u.color == 1:

u.color = 0

k.parent.color = 0
k.parent.parent.color = 1

k = k.parent.parent

else:

if k == k.parent.right:

k = k.parent

self.left_rotate(k)

k.parent.color = 0

k.parent.parent.color = 1

self.right_rotate(k.parent.parent)

if k == self.root:

break

self.root.color = 0

# Printing the tree

Def __print_helper(self, node, indent, last):

If node != self.TNULL:

Sys.stdout.write(indent)

If last:

Sys.stdout.write(“R----“)

Indent += “ “

Else:

Sys.stdout.write(“L----“)

Indent += “| “

S_color = “RED” if node.color == 1 else “BLACK”

Print(str(node.item) + “(“ + s_color + “)”)

Self.__print_helper(node.left, indent, False)

Self.__print_helper(node.right, indent, True)

Def preorder(self):

Self.pre_order_helper(self.root)

Def inorder(self):
Self.in_order_helper(self.root)

Def postorder(self):

Self.post_order_helper(self.root)

Def searchTree(self, k):

Return self.search_tree_helper(self.root, k)

Def minimum(self, node):

While node.left != self.TNULL:

Node = node.left

Return node

Def maximum(self, node):

While node.right != self.TNULL:

Node = node.right

Return node

Def successor(self, x):

If x.right != self.TNULL:

Return self.minimum(x.right)

Y = x.parent

While y != self.TNULL and x == y.right:

X=y

Y = y.parent

Return y

Def predecessor(self, x):

If (x.left != self.TNULL):

Return self.maximum(x.left)

Y = x.parent

While y != self.TNULL and x == y.left:

X=y

Y = y.parent

Return y
Def left_rotate(self, x):

Y = x.right

x.right = y.left

if y.left != self.TNULL:

y.left.parent = x

y.parent = x.parent

if x.parent == None:

self.root = y

elif x == x.parent.left:

x.parent.left = y

else:

x.parent.right = y

y.left = x

x.parent = y

def right_rotate(self, x):

y = x.left

x.left = y.right

if y.right != self.TNULL:

y.right.parent = x

y.parent = x.parent

if x.parent == None:

self.root = y

elif x == x.parent.right:

x.parent.right = y

else:

x.parent.left = y

y.right = x

x.parent = y

def insert(self, key):


node = Node(key)

node.parent = None

node.item = key

node.left = self.TNULL

node.right = self.TNULL

node.color = 1

y = None

x = self.root

while x != self.TNULL:

y=x

if node.item < x.item:

x = x.left

else:

x = x.right

node.parent = y

if y == None:

self.root = node

elif node.item < y.item:

y.left = node

else:

y.right = node

if node.parent == None:

node.color = 0

return

if node.parent.parent == None:

return

self.fix_insert(node)

def get_root(self):

return self.root
def delete_node(self, item):

self.delete_node_helper(self.root, item)

def print_tree(self):

self.__print_helper(self.root, “”, True)

if __name__ == “__main__”:

bst = RedBlackTree()

bst.insert(55)

bst.insert(40)

bst.insert(65)

bst.insert(60)

bst.insert(75)

bst.insert(57)

bst.print_tree()

print(“\nAfter deleting an element”)

bst.delete_node(40)

bst.print_tree(successfully)

OUTPUT:

RESULT:
Thus,the program for implementing Red Black tree in Python has been executed successfully.

16. SINGLY THREADED BINARY SEARCH TREE

AIM:

To write a python program to implement sinngly threaded binary search tree.

ALGORITHM:
1.Start the program
2.Import necessary modules typing ,forest and single threaded binary tree and traversal
3.Define duplicate function to data to file system
4.Insert data key and parameters
5.Dump the data key value pair
6.Call the function and with data as parameters
7.Display the data in ascending and descending order
8..Stop the program
PROGRAM:
From typing import Any

From forest.binary_trees import single_threaded_binary_trees

From forest.binary_trees import traversal

Class MyDatabase:

“””Example using threaded binary trees to build an index.”””

Def __init__(self) -> None:

Self._left_bst = single_threaded_binary_trees.LeftThreadedBinaryTree()

Self._right_bst = single_threaded_binary_trees.RightThreadedBinaryTree()

Def _persist(self, payload: Any) -> str:

“””Fake function pretent storing data to file system.

Returns

-------
Str

Path to the payload.

“””

Return f”path_to_{payload}”

Def insert_data(self, key: Any, payload: Any) -> None:

“””Insert data.

Parameters

----------

Key: Any

Unique key for the payload

Payload: Any

Any data

“””

Path = self._persist(payload=payload)

Self._left_bst.insert(key=key, data=path)

Self._right_bst.insert(key=key, data=path)

Def dump(self, ascending: bool = True) -> traversal.Pairs:

“””Dump the data.

Parameters

----------

Ascending: bool

The order of data.

Yields

------

Pairs

The next (key, data) pair.

“””

If ascending:

Return self._right_bst.inorder_traverse()
Else:

Return self._left_bst.reverse_inorder_traverse()

If __name__ == “__main__”:

# Initialize the database.

My_database = MyDatabase()

# Add some items.

My_database.insert_data(“Adam”, “adam_data”)

My_database.insert_data(“Bob”, “bob_data”)

My_database.insert_data(“Peter”, “peter_data”)

My_database.insert_data(“David”, “david_data”)

# Dump the items in ascending order.

Print(“Ascending…”)

For contact in my_database.dump():

Print(contact)

Print(“\nDescending…”)

# Dump the data in decending order.

For contact in my_database.dump(ascending=False):

Print(contact)

OUTPUT:
RESULT:

Thus, the program for singly threaded binary tree in python has been executed successful.

You might also like