DSA Rec-1
DSA Rec-1
DSA Rec-1
NAME : _____________________________
REG. NO : _____________________________
BRANCH : _____________________________
PRINCE SHRI VENKATESHWARA PADMAVATHY
ENGINEERING COLLEGE
PONMAR, CHENNAI- 600 048.
Name : ………………………………………………
Register No : ………………………………………………
Semester : ………………………………………………
Branch : ………………………………………………
AIM:
ALGORITHM:
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:
ALGORITHM:
Step-7: Print.
PROGRAM:
def factorial(x):
if x == 1:
return 1
else:
return (x * factorial(x-1))
num = 3
RESULT:
Thus,the program for implement recursive algorithms of Factorial in Python has been executed
successfully
B.SUM OF SEQUENCE
AIM:
ALGORITHM:
PROGRAM:
def sum(n):
total = 0
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:
ALGORITHM:
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.
PROGRAM:
import array
balance=array.array('i',[100,200,300])
print(balance)
print(balance[2])
print("-----------inserting an element---------------")
balance.insert(3,400)
balance.insert(4,150)
print("after insertion")
print(balance)
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:
ALGORITHM:
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.
PROGRAM:
Import os
Class _Node:
‘’’
‘’’
‘’’
Self._element = element
Self._link = link
Class LinkedList:
‘’’
‘’’
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):
‘’’
‘’’
Return self._size
Def isempty(self):
‘’’
‘’’
Return self._size == 0
‘’’
‘’’
Newest = _Node(e, None)
If self.isempty():
Self._head = newest
Else:
Self._tail._link = newest
Self._tail = newest
Self._size +=1
‘’’
‘’’
If self.isempty():
Self._head = newest
Self._tail = newest
Else:
Newest._link = self._head
Self._head = newest
Self._size += 1
‘’’
Adds the passed element at the passed index position of the linked list.
‘’’
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
self._size += 1
def removeFirst(self):
‘’’
‘’’
If self.isempty():
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):
‘’’
‘’’
If self.isempty():
Return
P = self._head
If p._link == None:
E = p._element
Self._head = None
Else:
P = p._link
E = p._link._element
p._link = None
self._tail = p
self._size = self._size – 1
return e
‘’’
Removes element from the passed index position of the linked list.
‘’’
P = self._head
I = index – 1
If index == 0:
Return self.removeFirst()
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):
‘’’
‘’’
If self.isempty() == 0:
P = self._head
While p:
Print(p._element, end=’’)
P = p._link
Print(“NULL”)
Else:
Print(“Empty”)
‘’’
‘’’
P = self._head
Index = 0
While p:
If p._element == key:
Return index
P = p._link
Index += 1
Return -1
Def options():
‘’’
‘’’
Options_list = [‘Add Last’, ‘Add First’, ‘Add Anywhere’,
Print(“MENU”)
Return choice
Def switch_case(choice):
‘’’
‘’’
If choice == 1:
L.addLast(elem)
Elif choice == 2:
L.addFirst(elem)
Elif choice == 3:
L.addAnywhere(elem, index)
Elif choice == 4:
Elif choice == 5:
Elif choice == 7:
Print(“List: “, end=’’)
L.display()
Print(“\n”)
Elif choice == 8:
Print(“Size:”, len(L))
Print(“\n”)
Elif choice == 9:
If L.search(key) >= 0:
Else:
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
RESULT:
Thus,the program for implement singly linked list in Python has been executed successfully.
B. DOUBLY LINKED LIST
Import os
Class _Node:
‘’’
‘’’
‘’’
Initialses _element, _link and _prev with element, link and prev respectively.
‘’’
Self._element = element
Self._link = link
Self._prev = prev
Class DoublyLL:
‘’’
‘’’
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):
‘’’
‘’’
Return self._size
Def isempty(self):
‘’’
‘’’
Return self._size == 0
‘’’
Adds the passed element at the end of the doubly linked list.
‘’’
If self.isempty():
Self._head = newest
Else:
Self._tail._link = newest
Newest._prev = self._tail
Self._tail = newest
Self._size += 1
‘’’
Adds the passed element at the beginning of the doubly linked list.
‘’’
If self.isempty():
Self._head = newest
Self._tail = newest
Else:
Newest._link = self._head
Self._head._prev = newest
Self._head = newest
Self._size += 1
‘’’
‘’’
Elif self.isempty():
Self.addLast€
Elif index == 0:
Self.addFirst€
Self.addLast€
Else:
P = self._head
P = p._link
Newest._link = p._link
p._link._prev = newest
newest._prev = p
p._link = newest
self._size += 1
def removeFirst(self):
‘’’
‘’’
If self.isempty():
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):
‘’’
‘’’
If self.isempty():
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
‘’’
‘’’
Elif self.isempty():
Print(“List is empty”)
Elif index == 0:
Return self.removeFirst()
Return self.removeLast()
Else:
P = self._head
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”)
Def options():
‘’’
‘’’
Print(“MENU”)
Return choice
Def switch_case(choice):
‘’’
‘’’
Os.system(‘cls’)
If choice == 1:
DL.addLast(elem)
Elif choice == 2:
DL.addFirst(elem)
Elif choice == 3:
DL.addAnywhere(elem, index)
Elif choice == 4:
Elif choice == 5:
Elif choice == 6:
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
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
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:
ALGORITHM:
Step 2:Get the size from user and create the stack as list.
Step 5:get the choice from user whether to choose push,pop,display or exit.
PROGRAM:.
Class Stack:
Self.capacity = size
Self.top = -1
If self.isFull():
Exit(1)
Self.top = self.top + 1
Self.arr[self.top] = x
Def pop(self):
If self.isEmpty():
Exit(1)
Top = self.arr[self.top]
Self.top = self.top – 1
Return top
Def peek(self):
If self.isEmpty():
Exit(1)
Return self.arr[self.top
Def size(self):
Return self.top + 1
Def isEmpty(self):
Return self.size() == 0
Def isFull(self):
If __name__ == ‘__main__’:
Stack = Stack(3)
Stack.push(1) # Inserting 1 in the stack
If stack.isEmpty():
Else:
OUTPUT:
Top element is 3
RESULT:
Thus,the program for implement sack in Python has been executed successfully.
QUEUE
AIM:
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:
X=3
N = len(poly)
Result = 0
For I in range(n):
Sum = poly[i]
# Running a for loop to multiply x (n-i-1)
Sum = Sum * x
Print(result)
OUTPUT:
Result:5
ALGORITHM:
Step 1:Start the program.
Step 4:Define function infixtopostfix,if the operator not in operator list,append in the stack.
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.
PROGRAM:
Operators = set([‘+’, ‘-‘, ‘*’, ‘/’, ‘(‘, ‘)’, ‘^’]) # collection of Operators
Priority = {‘+’:1, ‘-‘:1, ‘*’:2, ‘/’:2, ‘^’:3} # dictionary having priorities of Operators
Def infixToPostfix(expression):
Output = ‘’
Output+= character
Stack.append(‘(‘)
Elif character==’)’:
Output+=stack.pop()
Stack.pop()
Else:
Output+=stack.pop()
Stack.append(character)
While stack:
Output+=stack.pop()
Return output
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):
Def isEmpty(self):
Return len(self.queue) == 0
Self.queue.append(data)
Def delete(self):
Try:
Max_val = 0
For I in range(len(self.queue)):
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)
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:
ALGORITHM:
PROGRAM:
Position = 0
Global iterations
Iterations = 0
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
If answer != -1:
Iterations,’iterations’)
Else:
OUTPUT:
B.BINARY SEARCH
AIM:
ALGORITHM:
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.
PROGRAM:
OUTPUT:
Target 12 found at position 10 in 4 iterations
SORTING:
A.BUBBLE SORT
AIM:
ALGORITHM:
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.
PROGRAM:
Def bubble_sort(alist):
No_swap = True
No_swap = False
If no_swap:
Return
Bubble_sort(alist)
B. SELECTION SORT
AIM:
ALGORITHM:
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.
PROGRAM:
Def selection_sort(alist):
Smallest = i
Smallest = j
Selection_sort(alist)
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:
ALGORITHM:
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.
PROGRAM:.
Quicksort(alist, start, p)
Quicksort(alist, p + 1, end)
Pivot = alist[start]
I = start + 1
J = end – 1
While True:
I=I+1
J=j–1
If I <= j:
Else:
Return j
Quicksort(alist, 0, len(alist))
OUTPUT:
RESULT:
Thus, the program for implementing sorting and searching algorithms in Python has been excited
successful.
8. IMPLEMENTATION OF HASH TABLE
AIM:
ALGORITHM:
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.
Def Hashing(keyvalue):
Return keyvalue % len(HashTable)
Hash_key = Hashing(keyvalue)
Hashtable[hash_key].append(value)
# Driver Code
Insert(HashTable, 9, ‘Delhi’)
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:
Self.left = None
Self.right = None
Self.data = data
# Insert Node
If self.data:
If self.left is None:
Self.left = Node(data)
Else:
Self.left.insert(data)
Else:
If self.right is None:
Self.right = Node(data)
Else:
Self.right.insert(data)
Else:
Self.data = data
Def PrintTree(self):
If self.left:
Self.left.PrintTree()
Print( self.data),
If self.right:
Self.right.PrintTree()
# Inorder traversal
Res = []
If root:
Res = self.inorderTraversal(root.left)
Res.append(root.data)
Return res
Res = []
If root:
Res.append(root.data)
Res = res + self.PreorderTraversal(root.left)
Return res
# Postorder traversal
Res = []
If root:
Res = self.PostorderTraversal(root.left)
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:
RESULT:
Thus,the program for implementing tree representation and traversal algorithms in Python has been
executed successfully.
AIM:
ALGORITHM:
PROGRAM:
Class Node:
Self.left = None
Self.right = None
Self.data = data
If 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
If self.left is None:
Return self.left.findval(lkpval)
If self.right is None:
Return self.right.findval(lkpval)
Else:
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:
ALGORITHM:
Step 7:Pop the smallest element from the list with the help of heappop.
PROGRAM:
Min Heap:
Import sys
Class MinHeap:
Self.maxsize = maxsize
Self.size = 0
Self.Heap = [0]*(self.maxsize + 1)
Self.Heap[0] = -1 * sys.maxsize
Self.FRONT = 1
Return pos//2
# at pos
Return 2 * pos
# at pos
Return (2 * pos) + 1
If not self.isLeaf(pos):
Self.swap(pos, self.leftChild(pos))
Self.minHeapify(self.leftChild(pos))
Else:
Self.swap(pos, self.rightChild(pos))
Self.minHeapify(self.rightChild(pos))
Return
Self.size+= 1
Self.Heap[self.size] = element
Current = self.size
Self.swap(current, self.parent(current))
Current = self.parent(current)
Def Print(self):
Str(self.Heap[2 * I + 1]))
Def minHeap(self):
Self.minHeapify(pos)
# Function to remove and return the minimum
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()
OUTPUT:
The minHeap is
Max Heap:
Import sys
Class MaxHeap:
Self.maxsize = maxsize
Self.size = 0
Self.Heap[0] = sys.maxsize
Self.FRONT = 1
# at pos
Return pos // 2
# at pos
Return 2 * pos
# at pos
Return True
Return False
Self.Heap[fpos])
If not self.isLeaf(pos):
If (self.Heap[self.leftChild(pos)] >
Self.Heap[self.rightChild(pos)]):
Self.swap(pos, self.leftChild(pos))
Self.maxHeapify(self.leftChild(pos))
Else:
Self.swap(pos, self.rightChild(pos))
Self.maxHeapify(self.rightChild(pos))
# Function to insert a node into the heap
Return
Self.size += 1
Self.Heap[self.size] = element
Current = self.size
Self.Heap[self.parent(current)]):
Self.swap(current, self.parent(current))
Current = self.parent(current)
Def Print(self):
Print(“PARENT : “ + str(self.Heap[i]) +
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()
OUTPUT:
The maxHeap is
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:
PROGRAM:
Class Graph:
# Constructor
Def __init__(self):
# default dictionary to store graph
Self.graph = defaultdict(list)
Def addEdge(self,u,v):
Self.graph[u].append(v)
Queue = []
Queue.append(s)
Visited[s] = True
While queue:
S = queue.pop(0)
For I in self.graph[s]:
If visited[i] == False:
Queue.append(i)
Visited[i] = True
# Driver code
# Create a graph given in
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)
g.BFS(2)
OUTPUT:
2031
Class Graph:
# Constructor
Def __init__(self):
Self.graph = defaultdict(list)
Self.graph[u].append(v)
# and print it
Visited.add(v)
Print(v, end=’ ‘)
Self.DFSUtil(neighbour, visited)
# recursive DFSUtil()
Visited = set()
Self.DFSUtil(v, visited)
# Driver’s code
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)
# Function call
g.DFS(2)
OUTPUT:
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:
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():
Self.V = vertices
Min = 1e7
For v in range(self.V):
Min = dist[v]
Min_index = v
Return min_index
Dist[src] = 0
U = self.minDistance(dist, sptSet)
sptSet[u] = True
For v in range(self.V):
If (self.graph[u][v] > 0 and
self.printSolution(dist)
# Driver program
G = Graph(9)
[0, 8, 0, 7, 0, 4, 0, 0, 2],
[0, 0, 0, 0, 0, 2, 0, 1, 6],
[0, 0, 2, 0, 0, 0, 6, 7, 0]
g.dijkstra(0)
OUTPUT:
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:
ALGORITHM:
PROGRAM:
Class Graph():
Self.V = vertices
Print(“Edge \tWeight”)
Min = sys.maxsize
For v in range(self.V):
Min = key[v]
Min_index = v
Return min_index
Def primMST(self):
Key[0] = 0
U = self.minKey(key, mstSet)
mstSet[u] = True
# Update dist value of the adjacent vertices
For v in range(self.V):
Key[v] = self.graph[u][v]
Parent[v] = u
Self.printMST(parent)
# Driver’s code
If __name__ == ‘__main__’:
G = Graph(5)
[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.
AIM:
To write a python program to implement the red and black tree structure.
ALGORITHM:
8.Call the function to traverse and rotate the tree structure to balance
PROGRAM:
Import sys
# Node creation
Class Node():
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
If node != TNULL:
Sys.stdout.write(node.item + “ “)
Self.pre_order_helper(node.left)
Self.pre_order_helper(node.right)
# Inorder
If node != TNULL:
Self.in_order_helper(node.left)
Sys.stdout.write(node.item + “ “)
Self.in_order_helper(node.right)
# Postorder
If node != TNULL:
Self.post_order_helper(node.left)
Self.post_order_helper(node.right)
Sys.stdout.write(node.item + “ “)
Return node
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
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
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
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
If node.item == key:
Z = node
Node = node.right
Else:
Node = node.left
If z == self.TNULL:
Return
Y=z
Y_original_color = y.color
If z.left == self.TNULL:
X = z.right
Self.__rb_transplant(z, z.right)
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)
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
If node != self.TNULL:
Sys.stdout.write(indent)
If last:
Sys.stdout.write(“R----“)
Indent += “ “
Else:
Sys.stdout.write(“L----“)
Indent += “| “
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)
Return self.search_tree_helper(self.root, k)
Node = node.left
Return node
Node = node.right
Return node
If x.right != self.TNULL:
Return self.minimum(x.right)
Y = x.parent
X=y
Y = y.parent
Return y
If (x.left != self.TNULL):
Return self.maximum(x.left)
Y = x.parent
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
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
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
x = x.left
else:
x = x.right
node.parent = y
if y == None:
self.root = node
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):
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()
bst.delete_node(40)
bst.print_tree(successfully)
OUTPUT:
RESULT:
Thus,the program for implementing Red Black tree in Python has been executed successfully.
AIM:
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
Class MyDatabase:
Self._left_bst = single_threaded_binary_trees.LeftThreadedBinaryTree()
Self._right_bst = single_threaded_binary_trees.RightThreadedBinaryTree()
Returns
-------
Str
“””
Return f”path_to_{payload}”
“””Insert data.
Parameters
----------
Key: Any
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)
Parameters
----------
Ascending: bool
Yields
------
Pairs
“””
If ascending:
Return self._right_bst.inorder_traverse()
Else:
Return self._left_bst.reverse_inorder_traverse()
If __name__ == “__main__”:
My_database = MyDatabase()
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”)
Print(“Ascending…”)
Print(contact)
Print(“\nDescending…”)
Print(contact)
OUTPUT:
RESULT:
Thus, the program for singly threaded binary tree in python has been executed successful.