DSA Record
DSA Record
Mark Staff
signature
8. HASH TABLES
11. HEAPS
PAGE NO : 1
AIM
ALGORITHM:
Step 1: Start
Step 3: Define the appropriate functions for stack operations such as push, pop, isEmpty, peek and size.
Step 4: Define the functions for queue operations like enqueue, dequeue, front, size.
Step 7:stop
1
PROGRAM:
class Stack:
self.items = []
def isEmpty(self):
return self.items == []
self.items.append(item)
def pop(self):
return self.items.pop()
self.items = []
def isEmpty(self):
return self.items == []
def enqueue(self,item):
self.items.append(item)
2
def dequeue(self):
return self.items.pop(0)
def front(self):
return self.items[len(self.items)-1]
def size(self):
return len(self.items)
s=Stack()
print(s.isEmpty())
s.push(5)
s.push('python')
print(s.peek())
s.push(True)
print(s.size())
print(s.isEmpty())
s.push(11.5)
print(s.pop())
print(s.pop())
print(s.size())
q=Queue()
3
print(q.isEmpty())
q.enqueue(5)
q.enqueue('python')
print(q.front())
q.enqueue(True)
print(q.size())
print(q.isEmpty())
q.enqueue(11.5)
print(q.dequeue())
print(q.dequeue())
print(q.size())
4
OUTPUT:
True
python
False
11.5
True
True
python
False
python
RESULT:
Thus the stack and queue ADTs are implemented using python classes.
5
EX.NO : 2
AIM:
ALGORITHM:
Step 1: Start
Step 3: If the number of terms (n) is less than 0, print “Invalid Input”.
Step 6: Stop.
6
PROGRAM:
def recursive_fibonacci(n):
if n <= 1:
return n
else:
return(recursive_fibonacci(n-1) + recursive_fibonacci(n-2))
if n_terms< 0:
elifn_terms ==0:
print("Fibonacci series:")
print(0)
else:
print("Fibonacci series:")
for i in range(n_terms):
print(recursive_fibonacci(i))
7
OUTPUT:
Fibonacci series
0,1,1,2,3,5,8,13,21,34
RESULT:
Thus, the Fibonacci series using recursion is implemented using python classes.
8
EX.NO : 03
AIM:
ALGORITHM:
1. The append() method is called on a ListADT object, with a single argument item.
2. The method begins by accessing the items attribute of the object, which is a list.
3. The append() method is then called on the items list, passing in the item argument as a
parameter.
4. item is added to the end of the list and the size of the list increases by 1.
5. The append() method exits and the updated items list is now stored as an attribute of the
ListADT object.
6. The other methods in the class ListADT works similarly and are simple implementation of the
python list functions like insert, remove, index, pop with an additional check of empty list in
is_empty() function.
9
PROGRAM:
class ListADT:
self.items = []
def is_empty(self):
return len(self.items) == 0
def size(self):
return len(self.items)
self.items.append(item)
self.items.insert(index, item)
self.items.remove(item)
return self.items.index(item)
return self.items.pop(index)
return str(self.items)
my_list = ListADT()
my_list.append(1)
my_list.append(2)
10
my_list.append(3)
print(my_list)
my_list.remove(2)
print(my_list)
my_list.pop()
print(my_list)
OUTPUT:
[1, 2, 3]
[1, 3]
[1]
RESULT:
Thus the program implement list ADT using python arrays has been executed.
11
EX.NO : 4
AIM:
ALGORITHM:
Step 1: Start
Step 2: Create classes Node and Linked List for creating a node and liking with the head node.
Step 3: Define proper methods in the class such as append, display for adding elements and display
operations in the linked list.
Step 6: Stop.
12
PROGRAM:
class Node:
self.data = data
self.next = None
class LinkedList:
self.head = None
self.last_node = None
if self.last_node is None:
self.head = Node(data)
self.last_node = self.head
else:
self.last_node.next = Node(data)
self.last_node = self.last_node.next
def display(self):
current = self.head
current = current.next
a_llist = LinkedList()
13
for i in range(n):
a_llist.append(data)
a_llist.display()
14
OUTPUT :
Enter data item: How many elements would you like to add? 5
> 15
RESULT:
Thus the program for linked list implementation of list has been executed.
15
EX.NO : 5(A)
AIM:
ALGORITHM:
Step1: Start
Step 2: Initialise top =0 and read the maximum size of the stack.
Step 6: Stop
16
PROGRAM:
top=0
def createStack():
stack=[]
return stack
def isEmpty(stack):
return len(stack)==0
def Push(stack,item):
stack.append(item)
print("Pushed to stack",item)
def Pop(stack):
if isEmpty(stack):
return stack.pop()
stack=createStack()
while True:
print("1.Push")
print("2.Pop")
print("3.Display")
print("4.Quit")
if ch==1:
if top<mymax:
17
Push(stack,item)
top+=1
else:
print("Stack overflow")
elifch==2:
print(Pop(stack))
elifch==3:
print(stack)
else:
print("Exit")
break
18
OUTPUT:
1.Push
2.Pop
3.Display
4.Quit
1.Push
2.Pop
3.Display
4.Quit
1.Push
2.Pop
3.Display
4.Quit
1.Push
2.Pop
3.Display
4.Quit
19
Enter your choice:3
1.Push
2.Pop
3.Display
4.Quit
300
1.Push
2.Pop
3.Display
4.Quit
['100', '200']
RESULT:
20
EX.NO : 5(B)
AIM:
ALGORITHM:
Step1: Start
Step 2: Initialise front, rear =0 and read the maximum size of the queue.
Step 6: Stop
21
PROGRAM:
front=0
rear=0
def createQueue():
queue=[]
return queue
def isEmpty(queue):
return len(queue)==0
def enqueue(queue,item):
queue.append(item)
print("Enqueued to queue",item)
def dequeue(queue):
if isEmpty(queue):
item=queue[0]
del queue[0]
return item
queue=createQueue()
while True:
print("1.Enqueue")
print("2.Dequeue")
print("3.Display")
22
print("4.Quit")
if ch==1:
if rear<mymax:
enqueue(queue,item)
rear+=1
else:
print("Queue is full")
elifch==2:
print(dequeue(queue))
elifch==3:
print(queue)
else:
print("Exit")
break
23
OUTPUT:
1. Enqueue
2. Dequeue
3. Display
4. Quit
1. Enqueue
2. Dequeue
3. Display
4. Quit
1. Enqueue
2. Dequeue
3. Display
4. Quit
1. Enqueue
2. Dequeue
24
3. Display
4. Quit
1. Enqueue
2. Dequeue
3. Display
4. Quit
300
1. Enqueue
2. Dequeue
3. Display
4. Quit
['100', '200']
RESULT:
25
EX.NO : 6(A)
AIM:
To write a python program to implement the application of Stack ADT – Infix to postfix
expression
ALGORITHM:
Step 1: Start
Step 6: Stop.
26
PROGRAM:
class infix_to_postfix:
precedence={'^':5,'*':4,'/':4,'+':3,'-':3,'(':2,')':1}
self.items=[]
self.size=-1
def push(self,value):
self.items.append(value)
self.size+=1
def pop(self):
if self.isempty():
return 0
else:
self.size-=1
return self.items.pop()
def isempty(self):
if(self.size==-1):
return True
else:
return False
def seek(self):
if self.isempty():
return false
else:
return self.items[self.size]
def isOperand(self,i):
if i in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ':
27
return True
else:
return False
postfix=""
for i in expr:
if(len(expr)%2==0):
return False
elif(self.isOperand(i)):
postfix +=i
elif(i in '+-*/^'):
while(len(self.items)and self.precedence[i]<=self.precedence[self.seek()]):
postfix+=self.pop()
self.push(i)
elif i is '(':
self.push(i)
elif i is ')':
o=self.pop()
while o!='(':
postfix +=o
o=self.pop()
print(postfix)
#end of for
while len(self.items):
if(self.seek()=='('):
self.pop()
else:
28
postfix+=self.pop()
return postfix
s=infix_to_postfix()
result=s.infixtopostfix(expr)
if (result!=False):
OUTPUT:
A B C * + D E /H *
RESULT:
29
EX.NO : 6(B)
AIM:
To write a python program to implement the application of Queue ADT – Round Robin Schedule.
ALGORITHM:
Step 1: Start
Step 3: Define the Priority queue methods such as rotation and priority assignment.
Step 4: Read the process inputs and print the schedule output.
Step 6: Stop.
30
PROGRAM:
import random
import heapq
class Process:
pid = 0
self.priority = priority
self.time = time
self.used = 0
self.pid = Process.pid
Process.pid += 1
return self.priority<other.priority
def priority(p):
heapq.heapify(p)
current_process = heapq.heappop(p)
counter = 0
while current_process:
counter += 1
current_process.priority -= 3
current_process.time -= 1
31
current_process.pid, current_process.priority,current_process.time))
for item in p:
if current_process.time != 0:
heapq.heappush(p, current_process)
heapq.heapify(p)
if len(p) > 0:
current_process = heapq.heappop(p)
else:
break
return counter
def rotation(p):
rotation_time_length = 5
current_process = p.pop(0)
counter = 0
while current_process:
counter += 1
current_process.time -= 1
current_process.used += 1
print('\n[{}]: Running process {}, already occupied: {}, still need: {}'.format(counter,
current_process.pid,current_process.used,current_process.time))
for item in p:
if current_process.time == 0:
if len(p):
32
current_process = p.pop()
else:
return counter
else:
if current_process.used == rotation_time_length:
current_process.used = 0
p.append(current_process)
current_process = p.pop()
def main():
if method == 'A':
priority(p)
rotation(p)
else:
print()
main()
33
OUTPUT:
RESULT:
34
EX.NO : 6(C)
AIM:
To write a python program to implement the application of Linked List ADT – Polynomial
Addition.
ALGORITHM:
Step 1: Start
Step 3: Define the methods such as create_poly, show_poly and solve_poly for performing polynomial
addition.
Step 6: Stop
35
PROGRAM:
class Node :
self.data = data
self.power = power
self.next = None
self.data = data
self.power = power
class AddPolynomial :
self.head = None
def display(self) :
if (self.head == None) :
temp = self.head
if (temp != self.head) :
else :
if (temp.power != 0) :
temp = temp.next
36
print(end = "\n")
if (self.head == None) :
else :
node = None
temp = self.head
location = None
location = temp
temp = temp.next
else :
if (location == None) :
node.next = self.head
self.head = node
else :
node.next = location.next
location.next = node
RESULT = None
tail = None
node = None
37
first = self.head
second = other.head
node = Node(0, 0)
if (RESULT == None) :
RESULT = node
if (first.power == second.power) :
first = first.next
second = second.next
elif (first.power>second.power) :
node.updateRecord(first.data, first.power)
first = first.next
else :
node.updateRecord(second.data, second.power)
second = second.next
node.updateRecord(first.data, first.power)
first = first.next
else :
node.updateRecord(second.data, second.power)
second = second.next
if (tail == None) :
38
tail = node
else :
tail.next = node
tail = node
return RESULT
def main() :
poly1 = AddPolynomial()
poly2 = AddPolynomial()
RESULT = AddPolynomial()
poly1.addNode(9, 3)
poly1.addNode(4, 2)
poly1.addNode(3, 0)
poly1.addNode(7, 1)
poly1.addNode(3, 4)
poly2.addNode(7, 3)
poly2.addNode(4, 0)
poly2.addNode(6, 1)
poly2.addNode(1, 2)
poly1.display()
poly2.display()
RESULT.head = poly1.addTwoPolynomials(poly2)
print(" RESULT")
RESULT.display()
39
OUTPUT:
RESULT:
40
EX.NO : 7(A)
AIM:
ALGORITHM:
Step 1: Start
In every iteration of selection sort, the minimum element from the unsorted subarray is picked
and moved to the sorted subarray.
Step 5: Stop.
41
PROGRAM:
import sys
A=[]
for i in range(n):
A.append(int(input()))
print(A)
for i in range(len(A)):
min_idx = i
min_idx = j
for i in range(len(A)):
print("%d" %A[i]),
42
OUTPUT:
11
22
33
44
55
RESULT:
43
EX.NO : 7(B)
AIM:
ALGORITHM:
Step 1: Start
3c: If the key element is smaller than its predecessor, compare it to the elements before. Move the greater
elements one position up to make space for the swapped element.Step 4: Display the sorted elements
Step 6: Stop.
44
PROGRAM:
def insertionSort(arr):
key = arr[i]
j = i-1
arr[j+1] = arr[j]
j -= 1
arr[j+1] = key
lst=[]
for i in range(n):
lst.append(int(input())
insertionSort(lst)
for i in range(n):
45
OUTPUT:
5 11 13 6 12
11
12
13
RESULT:
46
EX.NO : 7(C)
AIM:
ALGORITHM:
Step 1: Start
Step 6: Stop.
47
PROGRAM:
def partition(arr,low,high):
i = ( low-1 )
pivot = arr[high]
i = i+1
arr[i],arr[j] = arr[j],arr[i]
arr[i+1],arr[high] = arr[high],arr[i+1]
return ( i+1 )
def quickSort(arr,low,high):
pi = partition(arr,low,high)
lst=[]
for i in range(n):
lst.append(int(input()))
print(lst)
quickSort(lst,0,n-1)
for i in range(n):
48
OUTPUT:
RESULT:
49
EX.NO : 7(D)
AIM:
ALGORITHM:
Step 1: Start
Repeat the search procedure for all the elements in the list:
if item == value
Step 5: Stop
50
PROGRAM:
#Linear Search
lst=[]
flag=False
for i in range(0,n):
lst.append(int(input()))
print(lst)
for i in range(0,n):
if x==lst[i]:
flag=True
break
if flag==True:
else:
51
OUTPUT:
RESULT:
52
EX.NO : 7(E)
AIM
ALGORITHM
Step 1: Start
Repeat the search procedure for all the elements in the list:
if (x == arr[mid])
return mid
low = mid + 1
else
high = mid – 1
Step 5: Stop.
53
PROGRAM:
return False
else:
if target == data[mid]:
return True
else:
lst=[]
for i in range(n):
lst.append(int(input()))
lst.sort()
print(lst)
low=0
high=n-1
a=binary_search(lst,x,low,high)
if a==True:
print('Element found')
else:
54
OUTPUT:
RESULT:
55
EX.NO : 8
AIM:
ALGORITHM:
Step 1: Start
Step 3: Define the add, get and remove functions for the data.
Step 5: Define the hash function as key%size, and define the functions for data position, removal and
retrieval in the hash table.
Step 6: Stop
56
PROGRAM:
class Node:
self.key = key
self.val = val
self.next = None
class LinkedList:
p = self.prehead.next
while p:
if p.key == key:
return p
p = p.next
return None
p = self.search(key)
if p:
p.val = val
else:
p = self.search(key)
57
if p:
return p.val
else:
return None
prev = self.prehead
cur = prev.next
while cur:
if cur.key == key:
break
if cur:
prev.next = cur.next
def serialize(self):
p = self.prehead.next
ret = []
while p:
ret.append([p.key, p.val])
p = p.next
return ret
class MyHashMap:
self.size = 1033
58
def put(self, key, value):
h = self._hash(key)
self.arr[h].add(key, value)
h = self._hash(key)
ret = self.arr[h].get(key)
return ret
else:
return -1
h = self._hash(key)
self.arr[h].remove(key)
ob = MyHashMap()
ob.put(1, 1)
ob.put(2, 2)
print(ob.get(1))
print(ob.get(3))
ob.put(2, 1)
print(ob.get(2))
ob.remove(2)
print(ob.get(2))
ob = MyHashMap()
ob.put(1, 1)
ob.put(2, 2)
print(ob.get(1))
59
print(ob.get(3))
ob.put(2, 1)
print(ob.get(2))
ob.remove(2)
print(ob.get(2))
OUTPUT:
-1
-1
RESULT:
Thus the program for implementation of hash table has been executed.
60
EX.NO : 9(A)
AIM:
ALGORITHM:
Step 1: Start
Step 3: Define the insert method such that no element in the left side of the tree is greater and no element
in the right side of the tree is smaller than the root node.
Step 6: Stop.
61
PROGRAM:
class Node:
self.left = None
self.right = None
self.data = data
if self.data:
if data <self.data:
if self.left is None:
self.left = Node(data)
else:
self.left.insert(data)
if self.right is None:
self.right = Node(data)
else:
self.right.insert(data)
else:
self.data = data
def PrintTree(self):
if self.left:
62
self.left.PrintTree()
print( self.data),
if self.right:
self.right.PrintTree()
root = Node(27)
root.insert(14)
root.insert(35)
root.insert(31)
root.insert(10)
root.insert(19)
root.PrintTree()
OUTPUT:
10 14 19 27 31 35
RESULT:
Thus the program for implementation Binary tree representation has been executed.
63
EX.NO : 9 (B)
AIM:
ALGORITHM:
Step 1: Start
Step 3: Define the pre order, post order and inorder methods for data.
Step 6: Stop
64
PROGRAM:
class Node:
self.left = None
self.right = None
self.val = item
def inorder(root):
if root:
inorder(root.left)
inorder(root.right)
def postorder(root):
if root:
postorder(root.left)
postorder(root.right)
def preorder(root):
if root:
preorder(root.left)
preorder(root.right)
root = Node(1)
root.left = Node(2)
65
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
inorder(root)
preorder(root)
postorder(root)
66
OUTPUT:
Inorder traversal
4->2->5->1->3->
Preorder traversal
1->2->4->5->3->
Postorder traversal
4->5->2->3->1->
RESULT:
Thus, the program for implementation of tree traversals has been executed.
67
EX.NO : 10
AIM:
ALGORITHM:
Step1: Start
Step 3: Define the insert method of the BST with proper condition for insertion.
Step 6: Stop
68
PROGRAM:
class Node:
self.key = key
self.left = None
self.right = None
if self is None:
self = Node(key)
return
if key <self.key:
if self.left:
self.left.insert(key)
else:
self.left = Node(key)
return
else:
if self.right:
self.right.insert(key)
else:
self.right = Node(key)
69
return
class binarySearchTree:
self.root = Node(key)
self.root.insert(key)
def inorder(root):
if root:
inorder(root.left)
print(root.key)
inorder(root.right)
BST = binarySearchTree(6)
BST.insert(3)
BST.insert(9)
BST.insert(1)
BST.insert(5)
BST.insert(7)
BST.insert(11)
inorder(BST.root)
70
OUTPUT:
11
RESULT:
71
EX.NO : 11
DATE : HEAPS
PAGE NO :72
AIM:
ALGORITHM:
Step 1: Start
Step 7: Stop
72
PROGRAM:
class MinHeap:
self.heap_list = [0]
self.current_size = 0
while i // 2 > 0:
i = i // 2
self.heap_list.append(k)
self.current_size += 1
self.sift_up(self.current_size)
mc = self.min_child(i)
if self.heap_list[i] >self.heap_list[mc]:
i = mc
73
if (i * 2)+1 >self.current_size:
return i * 2
else:
if self.heap_list[i*2] <self.heap_list[(i*2)+1]:
return i * 2
else:
return (i * 2) + 1
def delete_min(self):
if len(self.heap_list) == 1:
root = self.heap_list[1]
self.heap_list[1] = self.heap_list[self.current_size]
*self.heap_list, _ = self.heap_list
self.current_size -= 1
self.sift_down(1)
return root
my_heap = MinHeap()
my_heap.insert(5)
my_heap.insert(6)
my_heap.insert(7)
my_heap.insert(9)
my_heap.insert(13)
my_heap.insert(11)
my_heap.insert(10)
print(my_heap.delete_min())
74
OUTPUT:
RESULT:
75
EX.NO : 12(A)
AIM:
ALGORITHM:
Step 1: Start
Step 5: Stop
76
PROGRAM:
def add_vertex(v):
global graph
global vertices_no
if v in graph:
else:
vertices_no = vertices_no + 1
graph[v] = []
global graph
if v1 not in graph:
else:
temp = [v2, e]
graph[v1].append(temp)
def print_graph():
global graph
print(vertex, " -> ", edges[0], " edge weight: ", edges[1])
77
graph = {}
vertices_no = 0
add_vertex(1)
add_vertex(2)
add_vertex(3)
add_vertex(4)
add_edge(1, 2, 1)
add_edge(1, 3, 1)
add_edge(2, 3, 3)
add_edge(3, 4, 4)
add_edge(4, 1, 5)
print_graph()
78
OUTPUT:
3 -> 4
edge weight: 4
Internal representation: {1: [[2, 1], [3, 1]], 2: [[3, 3]], 3: [[4, 4]], 4: [[1, 5]]}
RESULT:
79
EX.NO : 12(B)
AIM:
ALGORITHM:
Step 1: Start
print (node)
visited.add(node)
Step 5: Stop
80
PROGRAM:
graph = {
'A' : ['B','C'],
'C' : ['F'],
'D' : [],
'E' : ['F'],
'F' : []
visited = set()
print (node)
visited.add(node)
81
OUTPUT:
RESULT:
Thus the depth first search algorithm for graph has been implemented.
82
EX.NO : 12(C)
AIM:
ALGORITHM:
Step 1: Start
Step 2: Create a graph using the dictionary in python and two lists.
visited.append(node)
queue.append(node)
Step 5: Stop
83
PROGRAM:
graph = {
'A' : ['B','C'],
'C' : ['F'],
'D' : [],
'E' : ['F'],
'F' : []
visited = []
queue = []
visited.append(node)
queue.append(node)
while queue:
s = queue.pop(0)
visited.append(neighbour)
queue.append(neighbour)
84
OUTPUT:
ABCDEF
RESULT:
Thus the program for breadth first traversal for a graph has been implemented
85
EX.NO : 13
AIM:
ALGORITHM:
Step 1: Start
1) Create a set (shortest path tree set) that keeps track of vertices included in shortest path tree,
i.e., whose minimum distance from source is calculated and finalized.
2) Assign a distance value to all vertices in the input graph. Initialize all distance values as INFINITE.
Assign distance value as 0 for the source vertex so that it is picked first.
a) Pick a vertex u which is not there in sptSet and has minimum distance value.
b) Include u to sptSet.
Step 5: Stop
86
PROGRAM:
import sys
def to_be_visited():
global visited_and_distance
v = -10
if visited_and_distance[index][0] == 0 \
visited_and_distance[v][1]):
v = index
return v
[0, 0, 1, 0],
[0, 0, 0, 1],
[0, 0, 0, 0]]
[0, 0, 0, 1],
[0, 0, 0, 0]]
number_of_vertices = len(vertices[0])
for i in range(number_of_vertices-1):
visited_and_distance.append([0, sys.maxsize])
87
for vertex in range(number_of_vertices):
to_visit = to_be_visited()
if vertices[to_visit][neighbor_index] == 1 and \
visited_and_distance[neighbor_index][0] == 0:
new_distance = visited_and_distance[to_visit][1] \
+ edges[to_visit][neighbor_index]
if visited_and_distance[neighbor_index][1] >new_distance:
visited_and_distance[neighbor_index][1] = new_distance
visited_and_distance[to_visit][0] = 1
i=0
i=i+1
88
OUTPUT:
RESULT:
Thus the program for single source shortest path algorithm has been implemented.
89
EX.NO : 14(A)
AIM:
ALGORITHM:
Step 1: Start
Create a priority queue Q that contains all the edges of the graph.
IF the edge obtained in Step 4 connects two different trees, then Add it to the forest
ELSE
Step 4: Print the minimum spanning tree which has been generated.
Step 5: Stop
90
PROGRAM:
class Graph:
self.V = vertices
self.graph = []
self.graph.append([u, v, w])
if parent[i] == i:
return i
xroot = self.find(parent, x)
yroot = self.find(parent, y)
parent[xroot] = yroot
parent[yroot] = xroot
91
else:
parent[yroot] = xroot
rank[xroot] += 1
def KruskalMST(self):
RESULT = []
i=0
e=0
parent.append(node)
rank.append(0)
while e <self.V-1:
u, v, w = self.graph[i]
i += 1
x = self.find(parent, u)
y = self.find(parent, v)
if x != y:
e += 1
92
RESULT.append([u, v, w])
self.union(parent, rank, x, y)
g = Graph(4)
g.addEdge(0, 1, 10)
g.addEdge(0, 2, 6)
g.addEdge(0, 3, 5)
g.addEdge(1, 3, 15)
g.addEdge(2, 3, 4)
g.KruskalMST()
93
OUTPUT:
2-3=4
0-3=5
0 - 1 = 10
RESULT:
Thus the program for Minimum spanning tree using Kruskal algorithm has been implemented.
94
EX.NO : 14(B)
AIM:
ALGORITHM:
Step 1: Start
Find all the edges that connect the tree to new vertices, find the minimum and add it to the tree
Step 4: Print the minimum spanning tree which has been generated.
Step 5: Stop
95
PROGRAM:
INF = 9999999
V=5
selected = [0, 0, 0, 0, 0]
no_edge = 0
selected[0] = True
print("Edge : Weight\n")
minimum = INF
x=0
y=0
for i in range(V):
if selected[i]:
for j in range(V):
minimum = G[i][j]
x=i
96
y=j
selected[y] = True
no_edge += 1
OUTPUT:
Edge : Weight
0-1:9
1-3:19
3-4:31
3-2:51
RESULT:
Thus the program for minimum spanning tree using Prim’s algorithm has been implemented.
97
98