0% found this document useful (0 votes)
31 views83 pages

DSA Lab Manual

The document outlines experiments on data structures and algorithms. It includes implementations of stack, queue, linked list, binary search tree and graph traversal algorithms. Applications of different data structures like stack and queue are also presented.

Uploaded by

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

DSA Lab Manual

The document outlines experiments on data structures and algorithms. It includes implementations of stack, queue, linked list, binary search tree and graph traversal algorithms. Applications of different data structures like stack and queue are also presented.

Uploaded by

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

INDEX

Date PO’s &


Name of the CO’s
Sno Date of PSO’s Marks Sign
Experiment Mapped
Completion Mapped
Simple ADTS-Python
1
Classes
Recursive Algorithm-
2
Fibonacci series
Linked List
3
Implementations of List

4A Stack ADT

4B Queue ADT

5A Application of Stack ADT

5B Application of Queue ADT

5C Application of List ADT

6A Selection Sort

6B Insertion Sort

6C Quick Sort

6D Linear Search

6E Binary Search
7 Hash Tables

8A Binary Tree Representation

8B Tree Traversal Algorithm

9 Binary Search Tree

10 Heaps

11A Graph Representation

11B Depth First Search

11C Breath First Search

Single Source Shortest


12
Path

Minimum Spanning Tree -


13A
Kruskal’s Algorithm

Minimum Spanning Tree-


13B
Prim’s Algorithm

CONTENT BEYOND SYLLABUS

1 Single Inheritance

2 Multilevel Inheritance
EX.NO:1
SIMPLE ADTS-PYTHON CLASSES
DATE:

AIM:

ALGORITHM:

PROGRAM:

class Stack:
def __init__(self):
self.items = []

def isEmpty(self):
return self.items == []

def push(self, item):


self.items.append(item)

def pop(self):
return self.items.pop()

def peek(self):
return self.items[len(self.items) - 1]

def size(self):
return len(self.items)
class Queue:
def __init__(self):
self.items = []

def isEmpty(self):
return self.items == []

def enqueue(self,item):
self.items.append(item)

def dequeue(self):
return self.items.pop(0)
def front(self):
return self.items[len(self.items)-1]

def size(self):
return len(self.items)
s=Stack()
print('Stack operation examples')
print(s.isEmpty())
s.push(5)
s.push('python')
print(s.peek())
s.push(True)
print(s.size())
print(s.isEmpty())
s.push(11.5)
print(s.pop())
print(s.pop())
print(s.size())
q=Queue()
print('Queue operation examples')
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())
OUTPUT:

INFERENCE:

RESULT:

OUTCOME:
EX.NO:2
RECURSIVE ALGORITHM- FIBONACCI SERIES
DATE:

AIM:

ALGORITHM:

PROGRAM:

def recursive_fibonacci(n):
if n <= 1:
return n
else:
return(recursive_fibonacci(n-1) + recursive_fibonacci(n-2))
n_terms= int(input(“Enter the number of terms”))
if n_terms < 0:
print("Invalid input ! Please input a positive value")
elif n_terms ==0:
print("Fibonacci series:")
print(0)
else:
print("Fibonacci series:")
for i in range(n_terms):
print(recursive_fibonacci(i))
OUTPUT:

INFERENCE:

RESULT:

OUTCOME:
EX.NO:3
LINKED LIST IMPLEMENTATIONS OF LIST
DATE:

AIM:

ALGORITHM:

PROGRAM:

class Node:
def __init__(self, data):
self.data = data
self.next = None

class LinkedList:
def __init__(self):
self.head = None
self.last_node = None

def append(self, data):


if self.last_node is None:
self.head = Node(data)
self.last_node = self.head
else:
self.last_node.next = Node(data)
self.last_node = self.last_node.next
def display(self):
current = self.head
while current is not None:
print(current.data, end = ' ')
current = current.next

a_llist = LinkedList()
n = int(input('How many elements would you like to add? '))
for i in range(n):
data = int(input('Enter data item: '))
a_llist.append(data)
print('The linked list: ', end = '')
a_llist.display()

OUTPUT
INFERENCE:

RESULT:

OUTCOME:
EX.NO:4A
STACK ADT
DATE:

AIM:

ALGORITHM:

PROGRAM:

top=0
mymax=eval(input("Enter Maximum size of stack:"))
def createStack():
stack=[]
return stack
def isEmpty(stack):
return len(stack)==0
def Push(stack,item):
stack.append(item)
print("Pushed to stack",item)
def Pop(stack):
if isEmpty(stack):
return "stack underflow"
return stack.pop()
stack=createStack()
while True:
print("1.Push")
print("2.Pop")
print("3.Display")
print("4.Quit")
ch=int(input("Enter your choice:"))
if ch==1:
if top<mymax:
item=input("Enter any elements:")
Push(stack,item)
top+=1
else:
print("Stack overflow")
elif ch==2:
print(Pop(stack))
elif ch==3:
print(stack)
else:
print("Exit")
break

OUTPUT:
INFERENCE:

RESULT:

OUTCOME:
EX.NO:4B
QUEUE ADT
DATE:

AIM:

ALGORITHM:

PROGRAM:

front=0
rear=0
mymax=eval(input("Enter maximum size of queue:"))
def createQueue():
queue=[]
return queue

def isEmpty(queue):
return len(queue)==0
def enqueue(queue,item):
queue.append(item)
print("Enqueued to queue",item)
def dequeue(queue):
if isEmpty(queue):
return "Queue is empty"
item=queue[0]
del queue[0]
return item
queue=createQueue()
while True:
print("1.Enqueue")
print("2.Dequeue")
print("3.Display")
print("4.Quit")
ch=int(input("Enter your choice:"))
if ch==1:
if rear<mymax:
item=input("Enter any elements:")
enqueue(queue,item)
rear+=1
else:
print("Queue is full")
elif ch==2:
print(dequeue(queue))
elif ch==3:
print(queue)
else:
print("Exit")
break

OUTPUT:
INFERENCE:

RESULT:

OUTCOME:
EX.NO:5A
APPLICATION OF STACK ADT
DATE:

AIM:

ALGORITHM:

PROGRAM:

class infix_to_postfix:
precedence={'^':5,'*':4,'/':4,'+':3,'-':3,'(':2,')':1}
def __init__(self):
self.items=[]
self.size=-1
def push(self,value):
self.items.append(value)
self.size+=1
def pop(self):
if self.isempty():
return 0
else:
self.size-=1
return self.items.pop()
def isempty(self):
if(self.size==-1):
return True
else:
return False
def seek(self):
if self.isempty():
return false
else:
return self.items[self.size]
def isOperand(self,i):
if i in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ':
return True
else:
return False
def infixtopostfix (self,expr):
postfix=""
print('postfix expression after every iteration is:')
for i in expr:
if(len(expr)%2==0):
print("Incorrect infix expr")
return False
elif(self.isOperand(i)):
postfix +=i
elif(i in '+-*/^'):
while(len(self.items)and self.precedence[i]<=self.precedence[self.seek()]):
postfix+=self.pop()
self.push(i)
elif i is '(':
self.push(i)
elif i is ')':
o=self.pop()
while o!='(':
postfix +=o
o=self.pop()
print(postfix)
#end of for
while len(self.items):
if(self.seek()=='('):
self.pop()
else:
postfix+=self.pop()
return postfix
s=infix_to_postfix()
expr=input('enter the expression ')
result=s.infixtopostfix(expr)
if (result!=False):
print("the postfix expr of :",expr,"is",result)
OUTPUT:
INFERENCE:

RESULT:

OUTCOME:
EX.NO:5B
APPLICATION OF QUEUE ADT
DATE:

AIM:

ALGORITHM:

PROGRAM:

import random
import heapq

class Process:
pid = 0
def __init__(self, priority, time):
self.priority = priority
self.time = time
self.used = 0
self.pid = Process.pid
Process.pid += 1

def __lt__(self, other):


return self.priority < other.priority
def priority(p):
heapq.heapify(p)
current_process = heapq.heappop(p)
counter = 0
while current_process:
counter += 1
current_process.priority -= 3
current_process.time -= 1
print('\n[{}]: Running process {}, priority: {}, also need: {}'.format(counter,
current_process.pid, current_process.priority,current_process.time))
for item in p:
print('Process {}, priority is {}, still needs time: {}'.format(item.pid,item.priority,item.time))
if current_process.time != 0:
heapq.heappush(p, current_process)
heapq.heapify(p)
if len(p) > 0:
current_process = heapq.heappop(p)
else:
break
return counter

def rotation(p):
rotation_time_length = 5
current_process = p.pop(0)
counter = 0
while current_process:
counter += 1
current_process.time -= 1
current_process.used += 1
print('\n[{}]: Running process {}, already occupied: {}, still need: {}'.format(counter,
current_process.pid,current_process.used,current_process.time))
for item in p:
print('Process {} still needs time: {}'.format(item.pid, item.time))
if current_process.time == 0:
if len(p):
current_process = p.pop()
else:
return counter
else:
if current_process.used == rotation_time_length:
current_process.used = 0
p.append(current_process)
current_process = p.pop()

def main():
method = input("\n>>> Process scheduling ALGORITHM.\nA. Priority ALGORITHM\tB. Round
robin ALGORITHM\n> ")
p = [Process(random.randrange(97,100), random.randrange(1, 21)) for i in range(random.randrange(4,
9))]
if method == 'A':
priority(p)
elif method == 'B':
rotation(p)
else:
print('\n[ERROR]: Input error')
print()

if __name__ == '__main__':
main()

OUTPUT:
INFERENCE:

RESULT:

OUTCOME:
EX.NO:5C
APPLICATION OF LIST ADT
DATE:

AIM:

ALGORITHM:

PROGRAM:

class Node :
def __init__(self, data, power) :
self.data = data
self.power = power
self.next = None
def updateRecord(self, data, power) :
self.data = data
self.power = power
class AddPolynomial :
def __init__(self) :
self.head = None
def display(self) :
if (self.head == None) :
print("Empty Polynomial ")
print(" ", end = "")
temp = self.head
while (temp != None) :
if (temp != self.head) :
print("+", temp.data, end = "")
else :
print(temp.data, end = "")
if (temp.power != 0) :
print("x^", temp.power, end = " ",sep = "")
temp = temp.next
print(end = "\n")
def addNode(self, data, power) :
if (self.head == None) :

self.head = Node(data, power)


else :
node = None
temp = self.head
location = None
while (temp != None and temp.power >= power) :
location = temp
temp = temp.next
if (location != None and location.power == power) :
location.data = location.data + data
else :
node = Node(data, power)
if (location == None) :
node.next = self.head
self.head = node
else :
node.next = location.next
location.next = node
def addTwoPolynomials(self, other) :
RESULT = None
tail = None
node = None
first = self.head
second = other.head
while (first != None or second != None) :
node = Node(0, 0)
if (RESULT == None) :
RESULT = node
if (first != None and second != None) :
if (first.power == second.power) :
node.updateRecord(first.data + second.data, first.power)
first = first.next
second = second.next
elif (first.power > second.power) :
node.updateRecord(first.data, first.power)
first = first.next
else :
node.updateRecord(second.data, second.power)
second = second.next

elif (first != None) :


node.updateRecord(first.data, first.power)
first = first.next
else :
node.updateRecord(second.data, second.power)
second = second.next

if (tail == None) :
tail = node
else :
tail.next = node
tail = node
return RESULT
def main() :
poly1 = AddPolynomial()
poly2 = AddPolynomial()
RESULT = AddPolynomial()
poly1.addNode(9, 3)
poly1.addNode(4, 2)
poly1.addNode(3, 0)
poly1.addNode(7, 1)
poly1.addNode(3, 4)
poly2.addNode(7, 3)
poly2.addNode(4, 0)
poly2.addNode(6, 1)
poly2.addNode(1, 2)
print("\n Polynomial A")
poly1.display()
print(" Polynomial B")
poly2.display()
RESULT.head = poly1.addTwoPolynomials(poly2)
print(" RESULT")
RESULT.display()

if __name__ == "__main__": main()


OUTPUT:
INFERENCE:

RESULT:

OUTCOME:
EX.NO:6A
SELECTION SORT
DATE:

AIM:

ALGORITHM:

PROGRAM:

import sys
n=int(input(“enter the number of elements”))
A=[]
for i in range(n):
A.append(int(input()))
print(A)
for i in range(len(A)):
min_idx = i
for j in range(i+1, len(A)):
if A[min_idx] > A[j]:
min_idx = j

A[i], A[min_idx] = A[min_idx], A[i]

print ("Sorted array")


for i in range(len(A)):
print("%d" %A[i]),
OUTPUT:
INFERENCE:

RESULT:

OUTCOME:
EX.NO:6B
INSERTION SORT
DATE:

AIM:

ALGORITHM:

PROGRAM:

def insertionSort(arr):
for i in range(1, len(arr)):
key = arr[i]
j = i-1
while j >=0 and key < arr[j] :
arr[j+1] = arr[j]
j -= 1
arr[j+1] = key
lst=[]
n =int(input(“Enter the size of list”))
for i in range(n):
lst.append(int(input())
insertionSort(lst)
print ("Sorted array is:")
for i in range(n):
print ("%d" lst[i])
OUTPUT:
INFERENCE:

RESULT:

OUTCOME:
EX.NO:6C
QUICK SORT
DATE:

AIM:

ALGORITHM:

PROGRAM:

def partition(arr,low,high):
i = ( low-1 )
pivot = arr[high]
for j in range(low , high):
if arr[j] <= pivot:
i = i+1
arr[i],arr[j] = arr[j],arr[i]
arr[i+1],arr[high] = arr[high],arr[i+1]
return ( i+1 )
def quickSort(arr,low,high):
if low < high:
pi = partition(arr,low,high)
quickSort(arr, low, pi-1)
quickSort(arr, pi+1, high)
lst=[]
n = int(input('enter the elements'))
for i in range(n):
lst.append(int(input()))
print(lst)
quickSort(lst,0,n-1)
print ("Sorted array is:")
for i in range(n):
print (lst[i],end=" ")
OUTPUT:
INFERENCE:

RESULT:

OUTCOME:
EX.NO:6D
LINEAR SEARCH
DATE:

AIM:

ALGORITHM:

PROGRAM:

#Linear Search
n=int(input("Enter the size of list"))
lst=[]
flag=False
print("Enter the elements")
for i in range(0,n):
lst.append(int(input()))
print(lst)
x=int(input("Enter the element to search"))
for i in range(0,n):
if x==lst[i]:
flag=True
break
if flag==True:
print("The element is found")
else:
print("The element is not found")

OUTPUT:
INFERENCE:

RESULT:

OUTCOME:
EX.NO:6E
BINARY SEARCH
DATE:

AIM

ALGORITHM

PROGRAM:

def binary_search(data, target, low, high):


if low > high:
return False
else:
mid = (low + high) // 2
if target == data[mid]:
return True
elif target < data[mid]:
return binary_search(data, target, low, mid-1)
else:
return binary_search(data, target, mid + 1, high)
lst=[]
n =int(input("Enter the size of list"))
for i in range(n):
lst.append(int(input()))
lst.sort()
print(lst)
x=int(input("Enter the element to search"))
low=0
high=n-1
a=binary_search(lst,x,low,high)
if a==True:
print('Element found')
else:
print('Element Not found')
OUTPUT:
INFERENCE:

RESULT:

OUTCOME:
EX.NO: 7
HASH TABLES
DATE:

AIM:

ALGORITHM:

PROGRAM:

class Node:
def __init__(self, key, val):
self.key = key
self.val = val
self.next = None
class LinkedList:
def __init__(self):
self.prehead = Node(None, None)
def search(self, key):
p = self.prehead.next
while p:
if p.key == key:
return p
p = p.next
return None
def add(self, key, val):
p = self.search(key)
if p:
p.val = val
else:
node = Node(key, val)
self.prehead.next, node.next = node, self.prehead.next
def get(self, key):
p = self.search(key)
if p:
return p.val
else:
return None
def remove(self, key):
prev = self.prehead
cur = prev.next
while cur:
if cur.key == key:
break
prev, cur = cur, cur.next
if cur:
prev.next = cur.next
def serialize(self):
p = self.prehead.next
ret = []
while p:
ret.append([p.key, p.val])
p = p.next
return ret
class MyHashMap:
def __init__(self):
self.size = 1033
self.arr = [LinkedList() for _ in range(self.size)]
def _hash(self, key):
return key % self.size
def put(self, key, value):
h = self._hash(key)
self.arr[h].add(key, value)
def get(self, key):
h = self._hash(key)
ret = self.arr[h].get(key)
if ret is not None:
return ret
else:
return -1
def remove(self, key):
h = self._hash(key)
self.arr[h].remove(key)
ob = MyHashMap()
ob.put(1, 1)
ob.put(2, 2)
print(ob.get(1))
print(ob.get(3))
ob.put(2, 1)
print(ob.get(2))
ob.remove(2)
print(ob.get(2))
ob = MyHashMap()
ob.put(1, 1)
ob.put(2, 2)
print(ob.get(1))
print(ob.get(3))
ob.put(2, 1)
print(ob.get(2))
ob.remove(2)
print(ob.get(2))

OUTPUT:
INFERENCE:

RESULT:

OUTCOME:
EX.NO: 8A
BINARY TREE REPRESENTATION
DATE:

AIM:

ALGORITHM:

PROGRAM:

class Node:

def __init__(self, data):


self.left = None
self.right = None
self.data = data

def insert(self, data):


if self.data:
if data < self.data:
if self.left is None:
self.left = Node(data)
else:
self.left.insert(data)
elif data > self.data:
if self.right is None:
self.right = Node(data)
else:
self.right.insert(data)
else:
self.data = data

def PrintTree(self):
if self.left:
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:
INFERENCE:

RESULT:

OUTCOME:
EX.NO: 8B
TREE TRAVERSAL ALGORITHAM
DATE:

AIM:

ALGORITHM:

PROGRAM:

class Node:
def __init__(self, item):
self.left = None
self.right = None
self.val = item
def inorder(root):
if root:
inorder(root.left)
print(str(root.val) + "->", end='')
inorder(root.right)

def postorder(root):
if root:
postorder(root.left)
postorder(root.right)
print(str(root.val) + "->", end='')

def preorder(root):
if root:
print(str(root.val) + "->", end='')
preorder(root.left)
preorder(root.right)
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)

print("Inorder traversal ")


inorder(root)

print("\nPreorder traversal ")


preorder(root)

print("\nPostorder traversal ")


postorder(root)

OUTPUT:
INFERENCE:

RESULT:

OUTCOME:
EX.NO: 9
BINARY SEARCH TREE
DATE:

AIM:

To implement a binary search tree in python.

ALGORITHM:

Step1: Start
Step 2: Create a class Node and instantiate.
Step 3: Define the insert method of the BST with proper condition for insertion.
Step 4: Create a binary search tree class.
Step 5: Define the inorder traversal.
Step 6: Stop

PROGRAM:

class Node:

def __init__(self, key):


self.key = key
self.left = None
self.right = None

def insert(self, key):

if self is None:
self = Node(key)
return

if key < self.key:


if self.left:
self.left.insert(key)
else:
self.left = Node(key)
return
else:
if self.right:
self.right.insert(key)
else:
self.right = Node(key)
return

class binarySearchTree:
def __init__(self, key):
self.root = Node(key)

def insert(self, key):


self.root.insert(key)

def inorder(root):
if root:
inorder(root.left)
print(root.key)
inorder(root.right)

BST = binarySearchTree(6)

BST.insert(3)
BST.insert(9)
BST.insert(1)
BST.insert(5)
BST.insert(7)
BST.insert(11)
inorder(BST.root)

OUTPUT:
INFERENCE:

RESULT:

OUTCOME:
EX.NO: 10
HEAPS
DATE:

AIM:

ALGORITHM:

PROGRAM:

class MinHeap:
def __init__(self):
self.heap_list = [0]
self.current_size = 0

def sift_up(self, i):


while i // 2 > 0:
if self.heap_list[i] < self.heap_list[i // 2]:
self.heap_list[i], self.heap_list[i // 2] = self.heap_list[i // 2], self.heap_list[i]
i = i // 2

def insert(self, k):


self.heap_list.append(k)
self.current_size += 1
self.sift_up(self.current_size)

def sift_down(self, i):


while (i * 2) <= self.current_size:
mc = self.min_child(i)
if self.heap_list[i] > self.heap_list[mc]:
self.heap_list[i], self.heap_list[mc] = self.heap_list[mc], self.heap_list[i]
i = mc

def min_child(self, i):


if (i * 2)+1 > self.current_size:
return i * 2
else:
if self.heap_list[i*2] < self.heap_list[(i*2)+1]:
return i * 2
else:
return (i * 2) + 1

def delete_min(self):
if len(self.heap_list) == 1:
return 'Empty heap'
root = self.heap_list[1]
self.heap_list[1] = self.heap_list[self.current_size]
*self.heap_list, _ = self.heap_list
self.current_size -= 1
self.sift_down(1)
return root
my_heap = MinHeap()
my_heap.insert(5)
my_heap.insert(6)
my_heap.insert(7)
my_heap.insert(9)
my_heap.insert(13)
my_heap.insert(11)
my_heap.insert(10)
print(my_heap.delete_min())

OUTPUT:
INFERENCE:

RESULT:

OUTCOME:
EX.NO: 11A
GRAPH REPRESENTATION
DATE:

AIM:

ALGORITHM:

PROGRAM:

def add_vertex(v):
global graph
global vertices_no
if v in graph:
print("Vertex ", v, " already exists.")
else:
vertices_no = vertices_no + 1
graph[v] = []

def add_edge(v1, v2, e):


global graph
if v1 not in graph:
print("Vertex ", v1, " does not exist.")
elif v2 not in graph:
print("Vertex ", v2, " does not exist.")
else:
temp = [v2, e]
graph[v1].append(temp)
def print_graph():
global graph
for vertex in graph:
for edges in graph[vertex]:
print(vertex, " -> ", edges[0], " edge weight: ", edges[1])

graph = {}
vertices_no = 0
add_vertex(1)
add_vertex(2)
add_vertex(3)
add_vertex(4)
add_edge(1, 2, 1)
add_edge(1, 3, 1)
add_edge(2, 3, 3)
add_edge(3, 4, 4)
add_edge(4, 1, 5)
print_graph()
print ("Internal representation: ", graph)

OUTPUT:

.
INFERENCE:

RESULT:

OUTCOME:
EX.NO: 11B
DEPTH FIRST SEARCH
DATE:

AIM:

ALGORITHM:

PROGRAM:
graph = {
'A' : ['B','C'],
'B' : ['D', 'E'],
'C' : ['F'],
'D' : [],
'E' : ['F'],
'F' : []
}
visited = set()
def dfs(visited, graph, node):
if node not in visited:
print (node)
visited.add(node)
for neighbour in graph[node]:
dfs(visited, graph, neighbour)
dfs(visited, graph, 'A')

OUTPUT:

INFERENCE:

RESULT:

OUTCOME:
EX.NO: 11C
BREATH FIRST SEARCH
DATE:

AIM:

ALGORITHM:

PROGRAM:
graph = {
'A' : ['B','C'],
'B' : ['D', 'E'],
'C' : ['F'],
'D' : [],
'E' : ['F'],
'F' : []
}
visited = []
queue = []
def bfs(visited, graph, node):
visited.append(node)
queue.append(node)
while queue:
s = queue.pop(0)
print (s, end = " ")
for neighbour in graph[s]:
if neighbour not in visited:
visited.append(neighbour)
queue.append(neighbour)
bfs(visited, graph, 'A')
OUTPUT:

INFERENCE:

RESULT:

OUTCOME:
EX.NO: 12
SINGLE SOURCE SHORTEST PATH ALGORITHM
DATE:

AIM:

ALGORITHM:

PROGRAM:

import sys
def to_be_visited():
global visited_and_distance
v = -10
for index in range(number_of_vertices):
if visited_and_distance[index][0] == 0 \
and (v < 0 or visited_and_distance[index][1] <= \
visited_and_distance[v][1]):
v = index
return v

vertices = [[0, 1, 1, 0],


[0, 0, 1, 0],
[0, 0, 0, 1],
[0, 0, 0, 0]]
edges = [[0, 3, 4, 0],
[0, 0, 0.5, 0],
[0, 0, 0, 1],
[0, 0, 0, 0]]

number_of_vertices = len(vertices[0])

visited_and_distance = [[0, 0]]


for i in range(number_of_vertices-1):
visited_and_distance.append([0, sys.maxsize])

for vertex in range(number_of_vertices):

to_visit = to_be_visited()
for neighbor_index in range(number_of_vertices):
if vertices[to_visit][neighbor_index] == 1 and \
visited_and_distance[neighbor_index][0] == 0:
new_distance = visited_and_distance[to_visit][1] \
+ edges[to_visit][neighbor_index]

if visited_and_distance[neighbor_index][1] > new_distance:


visited_and_distance[neighbor_index][1] = new_distance

visited_and_distance[to_visit][0] = 1

i=0

print("The shortest distance of ",chr(ord('a') + i),\


" from the source vertex a is:",distance[1])
i=i+1
OUTPUT:

INFERENCE:

RESULT:

OUTCOME:
EX.NO: 13A
MINIMUM SPANNING TREE -KRUSKAL’S ALGORITHM
DATE:

AIM:

ALGORITHM:

PROGRAM:

from collections import defaultdict

class Graph:

def __init__(self, vertices):


self.V = vertices
self.graph = []

def addEdge(self, u, v, w):


self.graph.append([u, v, w])
def find(self, parent, i):
if parent[i] == i:
return i
return self.find(parent, parent[i])

def union(self, parent, rank, x, y):


xroot = self.find(parent, x)
yroot = self.find(parent, y)

if rank[xroot] < rank[yroot]:


parent[xroot] = yroot
elif rank[xroot] > rank[yroot]:
parent[yroot] = xroot
else:
parent[yroot] = xroot
rank[xroot] += 1

def KruskalMST(self):

RESULT = []
i=0
e=0

self.graph = sorted(self.graph, key=lambda item: item[2])

parent, rank = [], []

for node in range(self.V):


parent.append(node)
rank.append(0)

while e < self.V-1:


u, v, w = self.graph[i]
i += 1
x = self.find(parent, u)
y = self.find(parent, v)

if x != y:
e += 1
RESULT.append([u, v, w])
self.union(parent, rank, x, y)

print("Following are the edges in the constructed MST")


for u, v, weight in RESULT:
print("%d - %d = %d" % (u, v, weight))

g = Graph(4)
g.addEdge(0, 1, 10)
g.addEdge(0, 2, 6)
g.addEdge(0, 3, 5)
g.addEdge(1, 3, 15)
g.addEdge(2, 3, 4)
g.KruskalMST()

OUTPUT:
INFERENCE:

RESULT:

OUTCOME:
EX.NO: 13B
MINIMUM SPANNING TREE -PRIM’S ALGORITHM
DATE:

AIM:

ALGORITHM:

PROGRAM:

INF = 9999999
V=5
G = [[0, 9, 75, 0, 0],
[9, 0, 95, 19, 42],
[75, 95, 0, 51, 66],
[0, 19, 51, 0, 31],
[0, 42, 66, 31, 0]]
selected = [0, 0, 0, 0, 0]
no_edge = 0
selected[0] = True
print("Edge : Weight\n")
while (no_edge < V - 1):

minimum = INF
x=0
y=0
for i in range(V):
if selected[i]:
for j in range(V):
if ((not selected[j]) and G[i][j]):
# not in selected and there is an edge
if minimum > G[i][j]:
minimum = G[i][j]
x=i
y=j
print(str(x) + "-" + str(y) + ":" + str(G[x][y]))
selected[y] = True
no_edge += 1

OUTPUT:
INFERENCE:

RESULT:

OUTCOME:
EX.NO: 1
SINGLE INHERITANCE
DATE:

AIM:

ALGORITHM

PROGRAM

class person:
def __init__(self,name,gender,age):
self.name=name
self.gender=gender
self.age=age
def display(self):
print("Student name:",self.name)
print("Student gender:",self.gender)
print("Student age:",self.age)
class student(person):
def __init__(self,rollno,branch):
person.__init__(self,'Deepa','M',18)
self.rollno=rollno
self.branch=branch
def display1(self):
print("Student Rollno:",self.rollno)
print("Student Branch:",self.branch)
stud=student(123,'AIDS')
stud.display()
stud.display1()

OUTPUT:
INFERENCE:

RESULT:

OUTCOME:
EX.NO: 2
MULTILEVEL INHERITANCE
DATE:

AIM:

ALGORITHM

PROGRAM:

class person:
def __init__(self,name,gender,age):
self.name=name
self.gender=gender
self.age=age
def display(self):
print("Student name:",self.name)
print("Student gender:",self.gender)
print("Student age:",self.age)
class student(person):
def __init__(self,rollno,branch):
person.__init__(self,'aaa','M',18)
self.rollno=rollno
self.branch=branch
def display(self):
person.display(self)
print("Student Rollno:",self.rollno)
print("Student Branch:",self.branch)
class exam(student):
def __init__(self,mark1,mark2):
student.__init__(self,120,'cse')
self.mark1=mark1
self.mark2=mark2
def display(self):
student.display(self)
print("Subject1 mark:",self.mark1)
print("Subject2 mark:",self.mark2)
e=exam(98,93)
e.display()

OUTPUT
INFERENCE:

RESULT:

OUTCOME:

You might also like