CD3281 DS Lab Manual
CD3281 DS Lab Manual
class check:
def __init__(self):
self.n=[]
def add(self,a):
return self.n.append(a)
def remove(self,b):
self.n.remove(b)
def dis(self):
return(self,n)
obj1=check()
choice=1
while choice!=0:
print("0. Exit")
print("1. Add")
print("2. Delete")
print("3. Dispaly")
choice=int(input("Enter the choice"))
if(choice==1):
n=int(input("Enter number to append"))
obj1.add(n)
print("List",obj1.dis())
elif choice==2:
n=int(input("Enter number to remove"))
obj1.remove(n)
print("List",obj1.dis())
elif choice==3:
print("List",obj1.dis())
elif choice==0:
print("Exiting!")
else:
print("Invalid Choice")
print()
Output:
0. Exit
1. Add
2. Delete
3. Dispaly
Enter the choice 1
Enter number to append 23
List [23]
0. Exit
1. Add
2. Delete
3. Dispaly
Enter the choice 1
Enter number to append 45
List [23, 45]
0. Exit
1. Add
2. Delete
3. Dispaly
Enter the choice 1
Enter number to append 56
List [23, 45, 56]
0. Exit
1. Add
2. Delete
3. Dispaly
Enter the choice 3
List [23, 45, 56]
0. Exit
1. Add
2. Delete
3. Dispaly
Enter the choice 2
Enter number to remove 45
List [23, 56]
0. Exit
1. Add
2. Delete
3. Dispaly
Enter the choice 3
List [23, 56]
0. Exit
1. Add
2. Delete
3. Dispaly
Enter the choice 0
Exit
Output:
Enter number 5
Factorial
120
Ex:No: 2 b Implementation of Recursive Algorithm (Fibonacci Series)
def recur_fibo(n):
if n <= 1:
return n
else:
return(recur_fibo(n-1) + recur_fibo(n-2))
output:
How many terms? 10
Fibonacci sequence:
0
1
1
2
3
5
8
13
21
34
class singlylinkedlist:
def __init__(self):
self.head=None
def display(self):
temp=self.head
if self.head is None:
print("empty")
while temp is not None:
print(temp.data,end="\t")
temp=temp.next
def insertatbeg(self,data):
newNode=Node(data)
newNode.next=self.head
self.head=newNode
def insertatend(self,data):
newNode=Node(data)
temp=self.head
while temp.next is not None:
temp=temp.next
temp.next=newNode
def insertatintermediate(self,data):
newNode=Node(data)
temp=self.head
pos=3
for i in range(1,pos-1):
temp=temp.next
newNode.next=temp.next
temp.next=newNode
list1=singlylinkedlist()
Node1=Node(10)
list1.head=Node1
Node2=Node(20)
Node1.next=Node2
Node3=Node(30)
Node2.next=Node3
Node4=Node(40)
Node3.next=Node4
print("Node Creation")
list1.display()
print("\n")
print("Node insert at begin\n")
list1.insertatbeg(5)
list1.display()
print("\n")
print("Node insert at end\n")
list1.insertatend(50)
list1.display()
print("\n")
print("Node insert at intermediate")
list1.insertatintermediate(15)
print("\n")
list1.display()
Output:
Node Creation
10 20 30 40
Node insert at begin
5 10 20 30 40
Node insert at end
10 20 30 40 50
Node insert at intermediate
5 10 15 20 30 40
class node:
def __init__(self,data):
self.data=data
self.prev=None
self.next=None
class doublylinkedlist:
def __init__(self):
self.head=None
def display(self):
temp=self.head
if self.head is None:
print("empty")
while temp is not None:
print(temp.data,end="\t")
temp=temp.next
def insertatbeg(self,data):
temp=self.head
newnode=node(5)
newnode.next=temp
temp.prev=newnode
self.head=newnode
def deletion(self,data):
temp=self.head
self.head=temp.next
self.head.prev=None
temp.next=None
list1=doublylinkedlist()
node1=node(10)
list1.head=node1
node2=node(20)
node1.next=node2
node2.prev=node1
node3=node(30)
node2.next=node3
node3.prev=node2
node4=node(40)
node3.next=node4
node4.prev=node3
print("\ndoublylinkedlist:")
list1.display()
list1.insertatbeg(5)
print("\ninsert at beg:")
list1.display()
list1.deletion(5)
print("\ndelection:")
list1.display()
Output:
doublylinkedlist:
10 20 30 40
insert at beg:
5 10 20 30 40
deletion:
10 20 30 40
class CreateList:
#Declaring head and tail pointer as null.
def __init__(self):
self.head = Node(None);
self.tail = Node(None);
self.head.next = self.tail;
self.tail.next = self.head;
#This function will add the new node at the end of the list.
def add(self,data):
newNode = Node(data);
#Checks if the list is empty.
if self.head.data is None:
#If list is empty, both head and tail would point to new node.
self.head = newNode;
self.tail = newNode;
newNode.next = self.head;
else:
#tail will point to new node.
self.tail.next = newNode;
#New node will become new tail.
self.tail = newNode;
#Since, it is circular linked list tail will point to head.
self.tail.next = self.head;
class CircularLinkedList:
cl = CreateList();
#Adds data to the list
cl.add(1);
cl.add(2);
cl.add(3);
cl.add(4);
#Displays all the nodes present in the list
cl.display();
Output:
1
2
3
4
def isEmpty(self):
return self.items == []
def pop(self):
return self.items.pop()
def peek(self):
return self.items[len(self.items)-1]
def size(self):
return len(self.items)
s=Stack()
print(s.isEmpty())
s.push(4)
s.push('dog')
print(s.peek())
s.push(True)
print(s.size())
print(s.isEmpty())
s.push(8.4)
print(s.pop())
print(s.pop())
print(s.size())
OUTPUT:
True
dog
3
False
8.4
True
2
def isEmpty(self):
return self.items == []
def enqueue(self,item):
self.items.append(item)
def dequeue(self):
return self.items.pop()
def front(self):
return self.items[len(self.items)-1]
def size(self):
return len(self.items)
q=Queue()
print("Queue Opeartion example")
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:
queue operation example
True
Python
3
False
11.5
True
2
def add(A,B,m,n):
size=max(m,n)
sum=[0 for i in range(size)]
for i in range(0,m,1):
sum[i]=A[i]
for i in range(n):
sum[i]+=B[i]
return sum
def printpoly(poly,n):
for i in range(n):
print(poly[i],end=" ")
if(i!=0):
print("x^",i,end=" ")
if(i!=n-1):
print("+",end=" ")
if __name__=='__main__':
A=[5,0,10,6]
B=[1,2,4]
m=len(A)
n=len(B)
print("first polynomial is")
printpoly(A,m)
print("\n",end=" ")
print("second polynomial is:")
printpoly(B,n)
print("\n",end=" ")
sum=add(A,B,m,n)
size=max(m,n)
print("sum polynomial is:")
printpoly(sum,size)
output:
first polynomial is
5 + 0 x^ 1 + 10 x^ 2 + 6 x^ 3
second polynomial is:
1 + 2 x^ 1 + 4 x^ 2
sum polynomial is:
6 + 2 x^ 1 + 14 x^ 2 + 6 x^ 3
Output:
please enter the expression:
(a+b))(3)
expression is not correctly parenthesized
expression is not correctly parenthesized
expression is not correctly parenthesized
q=dequeue()
print("menu")
print("append<value>")
print("appendleft<value>")
print("pop")
print("popleft")
print("quit")
while True:
do=input("what would you like to do?").split()
operation=do[0].strip().lower()
if operation=='append':
q.append(int(do[1]))
elif operation=='appendleft':
q.append_left(int(do[1]))
elif operation=='pop':
if q.is_empty():
print("dequeue is empty")
else:
print("poped value from right:",q.pop())
elif operation=='popleft':
if q.is_empty():
print("dequeue is empty")
else:
print("poped value from left:",q.pop_left())
elif operation=='quit':
break
Output:
menu
append<value>
appendleft<value>
pop
popleft
quit
what would you like to do? append 1
what would you like to do? append 2
what would you like to do? pop
Popped value from right: 2
what would you like to do? pop
Popped value from right: 1
what would you like to do? append left 1
what would you like to do? append left 2
what would you like to do? pop
Popped value from right: 1
what would you like to do? pop
Popped value from right: 2
Output:
[5, 23, 32, 54, 65, 76]
Output:
element is found at index: 4
Output:
element is found at index 3
def checkPrime(n):
if n == 1 or n == 0:
return 0
return 1
def getPrime(n):
if n % 2 == 0:
n = n + 1
return n
def hashFunction(key):
capacity = getPrime(10)
return key % capacity
def removeData(key):
index = hashFunction(key)
hashTable[index] = 0
insertData(123, "apple")
insertData(432, "mango")
insertData(213, "banana")
insertData(654, "guava")
print(hashTable)
removeData(123)
print(hashTable)
Output:
[[], [], [123, 'apple'], [432, 'mango'], [213, 'banana'], [654, 'guava'], [], [],
[], []]
[[], [], 0, [432, 'mango'], [213, 'banana'], [654, 'guava'], [], [], [], []]
def inorderTraversal(root):
answer = []
inorderTraversalUtil(root, answer)
return answer
if root is None:
return
inorderTraversalUtil(root.left, answer)
answer.append(root.val)
inorderTraversalUtil(root.right, answer)
return
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.left.left = TreeNode(4)
root.left.right = TreeNode(5)
print(inorderTraversal(root))
Output:
[4, 2, 5, 1, 3]
Preorder Traversal
class TreeNode:
def __init__(self,val):
self.val = val
self.left = None
self.right = None
def preorderTraversal(root):
answer = []
preorderTraversalUtil(root, answer)
return answer
if root is None:
return
answer.append(root.val)
preorderTraversalUtil(root.left, answer)
preorderTraversalUtil(root.right, answer)
return
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.left.left = TreeNode(4)
root.left.right = TreeNode(5)
print(preorderTraversal(root))
Output:
[1, 2, 4, 5, 3]
Postorder Traversal:
class TreeNode:
def postorderTraversal(root):
answer = []
postorderTraversalUtil(root, answer)
return answer
if root is None:
return
postorderTraversalUtil(root.left, answer)
postorderTraversalUtil(root.right, answer)
answer.append(root.val)
return
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.left.left = TreeNode(4)
root.left.right = TreeNode(5)
print(postorderTraversal(root))
Output:
[4, 5, 2, 3, 1]
Ex:No: 10 Implemenattion of Binary Search
Tree
# Create a node
class Node:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
# Inorder traversal
def inorder(root):
if root is not None:
# Traverse left
inorder(root.left)
# Traverse root
print(str(root.key) + "->", end=' ')
# Traverse right
inorder(root.right)
# Insert a node
def insert(node, key):
return node
# Find the inorder successor
def minValueNode(node):
current = node
return current
# Deleting a node
def deleteNode(root, key):
root.key = temp.key
return root
root = None
root = insert(root, 8)
root = insert(root, 3)
root = insert(root, 1)
root = insert(root, 6)
root = insert(root, 7)
root = insert(root, 10)
root = insert(root, 14)
root = insert(root, 4)
Output:
Inorder traversal: 1-> 3-> 4-> 6-> 7-> 8-> 10-> 14->
Delete 10
Inorder traversal: 1-> 3-> 4-> 6-> 7-> 8-> 14->
def size(self):
return len(self.items)
def extract_max(self):
if self.size() == 0:
return None
largest = self.get_max()
self.items[0] = self.items[-1]
del self.items[-1]
self.max_heapify(0)
return largest
bheap = BinaryHeap()
print('Menu')
print('insert <data>')
print('max get')
print('max extract')
print('quit')
while True:
do = input('What would you like to do? ').split()
operation = do[0].strip().lower()
if operation == 'insert':
data = int(do[1])
bheap.insert(data)
elif operation == 'max':
suboperation = do[1].strip().lower()
if suboperation == 'get':
print('Maximum value: {}'.format(bheap.get_max()))
elif suboperation == 'extract':
print('Maximum value removed: {}'.format(bheap.extract_max()))
Output:
Case 1:
Menu
insert <data>
max get
max extract
quit
What would you like to do? insert 5
What would you like to do? insert 3
What would you like to do? insert -3
What would you like to do? insert 10
What would you like to do? insert 8
What would you like to do? max get
Maximum value: 10
What would you like to do? max extract
Maximum value removed: 10
What would you like to do? max extract
Maximum value removed: 8
What would you like to do? max extract
Maximum value removed: 5
What would you like to do? max extract
Maximum value removed: 3
What would you like to do? max get
Maximum value: -3
What would you like to do? quit
Case 2:
Menu
insert <data>
max get
max extract
quit
What would you like to do? insert 3
What would you like to do? insert 11
What would you like to do? insert 5
What would you like to do? max extract
Maximum value removed: 11
What would you like to do? max get
Maximum value: 5
What would you like to do? max extract
Maximum value removed: 5
What would you like to do? insert 15
What would you like to do? max get
Maximum value: 15
What would you like to do? quit
Ex:No:12. a Implementation of Breadth First Search
Program:
from collections import defaultdict
# Constructor
def __init__(self):
while queue:
Output:
2 0 3 1
class Graph:
# Constructor
def __init__(self):
# default dictionary to store graph
self.graph = defaultdict(list)
def DFS(self):
# create a set to store all visited vertices
visited = set()
# call the recursive helper function to print DFS traversal starting from all
# vertices one by one
for vertex in self.graph:
if vertex not in visited:
self.DFSUtil(vertex, visited)
# Driver's code
# create a graph given in the above diagram
if __name__ == "__main__":
print("Following is Depth First Traversal \n")
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.DFS()
Output:
0 1 2 3
Ex:No:13 Implementation of Single Source Shortest Path Algorithm
Program:
class Graph:
def __init__(self):
# dictionary containing keys that map to the corresponding vertex object
self.vertices = {}
def __iter__(self):
return iter(self.vertices.values())
class Vertex:
def __init__(self, key):
self.key = key
self.points_to = {}
def get_key(self):
"""Return key corresponding to this vertex object."""
return self.key
def get_neighbours(self):
"""Return all vertices pointed to by this vertex."""
return self.points_to.keys()
g is a Graph object.
source is a Vertex object in g.
"""
unvisited = set(g)
distance = dict.fromkeys(g, float('inf'))
distance[source] = 0
# mark as visited
unvisited.remove(closest)
# update distances
for neighbour in closest.get_neighbours():
if neighbour in unvisited:
new_distance = distance[closest] + closest.get_weight(neighbour)
if distance[neighbour] > new_distance:
distance[neighbour] = new_distance
return distance
g = Graph()
print('Undirected Graph')
print('Menu')
print('add vertex <key>')
print('add edge <src> <dest> <weight>')
print('shortest <source vertex key>')
print('display')
print('quit')
while True:
do = input('What would you like to do? ').split()
operation = do[0]
if operation == 'add':
suboperation = do[1]
if suboperation == 'vertex':
key = int(do[2])
if key not in g:
g.add_vertex(key)
else:
print('Vertex already exists.')
elif suboperation == 'edge':
src = int(do[2])
dest = int(do[3])
weight = int(do[4])
if src not in g:
print('Vertex {} does not exist.'.format(src))
elif dest not in g:
print('Vertex {} does not exist.'.format(dest))
else:
if not g.does_edge_exist(src, dest):
g.add_edge(src, dest, weight)
g.add_edge(dest, src, weight)
else:
print('Edge already exists.')
print('Edges: ')
for v in g:
for dest in v.get_neighbours():
w = v.get_weight(dest)
print('(src={}, dest={}, weight={}) '.format(v.get_key(),
dest.get_key(), w))
print()
Output:
Case 1:
Undirected Graph
Menu
add vertex <key>
add edge <src> <dest> <weight>
shortest <source vertex key>
display
quit
What would you like to do? add vertex 1
What would you like to do? add vertex 2
What would you like to do? add vertex 3
What would you like to do? add vertex 4
What would you like to do? add vertex 5
What would you like to do? add vertex 6
What would you like to do? add vertex 7
What would you like to do? add edge 1 2 10
What would you like to do? add edge 1 3 80
What would you like to do? add edge 3 4 70
What would you like to do? add edge 2 5 20
What would you like to do? add edge 2 3 6
What would you like to do? add edge 5 6 50
What would you like to do? add edge 5 7 10
What would you like to do? add edge 6 7 5
What would you like to do? shortest 1
Distances from 1:
Distance to 6: 45
Distance to 3: 16
Distance to 4: 86
Distance to 5: 30
Distance to 2: 10
Distance to 7: 40
Distance to 1: 0
Case 2:
Undirected Graph
Menu
add vertex <key>
add edge <src> <dest> <weight>
shortest <source vertex key>
display
quit
What would you like to do? add vertex 1
What would you like to do? add vertex 2
What would you like to do? add vertex 3
What would you like to do? add vertex 4
What would you like to do? add edge 1 2 10
What would you like to do? add edge 2 3 20
What would you like to do? add edge 3 4 30
What would you like to do? add edge 1 4 100
What would you like to do? shortest 1
Distances from 1:
Distance to 2: 10
Distance to 4: 60
Distance to 3: 30
Distance to 1: 0
def display(self):
print('Vertices: ', end='')
for v in self:
print(v.get_key(), end=' ')
print()
print('Edges: ')
for v in self:
for dest in v.get_neighbours():
w = v.get_weight(dest)
print('(src={}, dest={}, weight={}) '.format(v.get_key(),
dest.get_key(), w))
def __len__(self):
return len(self.vertices)
def __iter__(self):
return iter(self.vertices.values())
class Vertex:
def __init__(self, key):
self.key = key
self.points_to = {}
def get_key(self):
"""Return key corresponding to this vertex object."""
return self.key
def get_neighbours(self):
"""Return all vertices pointed to by this vertex."""
return self.points_to.keys()
def mst_krusal(g):
"""Return a minimum cost spanning tree of the connected graph g."""
mst = Graph() # create new Graph object to hold the MST
if len(g) == 1:
u = next(iter(g)) # get the single vertex
mst.add_vertex(u.get_key()) # add a copy of it to mst
return mst
# sort edges
edges.sort(key=lambda edge: edge[0].get_weight(edge[1]))
# add to mst
if not mst.does_vertex_exist(u.get_key()):
mst.add_vertex(u.get_key())
if not mst.does_vertex_exist(v.get_key()):
mst.add_vertex(v.get_key())
mst.add_edge(u.get_key(), v.get_key(), u.get_weight(v))
mst.add_edge(v.get_key(), u.get_key(), u.get_weight(v))
return mst
g = Graph()
print('Undirected Graph')
print('Menu')
print('add vertex <key>')
print('add edge <src> <dest> <weight>')
print('mst')
print('display')
print('quit')
while True:
do = input('What would you like to do? ').split()
operation = do[0]
if operation == 'add':
suboperation = do[1]
if suboperation == 'vertex':
key = int(do[2])
if key not in g:
g.add_vertex(key)
else:
print('Vertex already exists.')
elif suboperation == 'edge':
src = int(do[2])
dest = int(do[3])
weight = int(do[4])
if src not in g:
print('Vertex {} does not exist.'.format(src))
elif dest not in g:
print('Vertex {} does not exist.'.format(dest))
else:
if not g.does_edge_exist(src, dest):
g.add_edge(src, dest, weight)
g.add_edge(dest, src, weight)
else:
print('Edge already exists.')
Output:
Case 1:
Undirected Graph
Menu
add vertex <key>
add edge <src> <dest> <weight>
mst
display
quit
What would you like to do? add vertex 1
What would you like to do? add vertex 2
What would you like to do? add vertex 3
What would you like to do? add vertex 4
What would you like to do? add vertex 5
What would you like to do? add vertex 6
What would you like to do? add edge 1 2 10
What would you like to do? add edge 1 5 30
What would you like to do? add edge 1 4 40
What would you like to do? add edge 2 5 20
What would you like to do? add edge 4 5 40
What would you like to do? add edge 5 3 40
What would you like to do? add edge 5 6 70
What would you like to do? add edge 3 6 50
What would you like to do? mst
Minimum Spanning Tree:
Vertices: 1 2 3 4 5 6
Edges:
(src=1, dest=4, weight=40)
(src=1, dest=2, weight=10)
(src=2, dest=5, weight=20)
(src=2, dest=1, weight=10)
(src=3, dest=5, weight=40)
(src=3, dest=6, weight=50)
(src=4, dest=1, weight=40)
(src=5, dest=2, weight=20)
(src=5, dest=3, weight=40)
(src=6, dest=3, weight=50)
Case 2:
Undirected Graph
Menu
add vertex <key>
add edge <src> <dest> <weight>
mst
display
quit
What would you like to do? add vertex 1
What would you like to do? add vertex 2
What would you like to do? add vertex 3
What would you like to do? add edge 1 2 10
What would you like to do? add edge 1 3 20
What would you like to do? add edge 2 3 30
What would you like to do? mst
Minimum Spanning Tree:
Vertices: 1 2 3
Edges:
(src=1, dest=3, weight=20)
(src=1, dest=2, weight=10)
(src=2, dest=1, weight=10)
(src=3, dest=1, weight=20)