P
ractical no.01
Q.1: Write a program to implement Abstract Data Type (ADT)
1. Using Built in Data Type (List)
A) Code:-
list1 = [10,20,30,40,50]
print("printing element in python by using different
ways") print("Print list by print()method",list1)
print("print list by for
loop") for i in list1:
print(i,end="")
print()
print("print list by*
asterisk") print(*list1)
print("print list by comma
separator") print(list1,sep=",")
Output:-
printing element in python by using different
ways Print list by print()method [10, 20, 30, 40,
50] print list by for loop
1020304050
print list by*
asterisk 10 20 30 40
50
print list by comma
separator [10, 20, 30, 40, 50]
B) Code:-
list1 = [10,20,30,40,50]
print(list1[0])
print(list1[1:4]
)
print(list1[1:3]
) print(list1[-
1])
print(list1[3:-1])
print(list1[0:2:2])
print(list1[0:5])
Output:-
10
[20, 30, 40]
[20, 30]
50
[40]
[10]
[10, 20, 30, 40, 50]
C) Code:-
le = [10,20,30,40,50,60,70,80,90,100,110,120,130,140,150,160,170,180,190,200]
print("printing the list element using print:\
n",le) print("printing the list element using for
loop:") for i in le:
print(i,end=" ")
print("\nprinting the list element *
asterisk:") print(*le)
print("printing the list element by comma separator:")
print(le,sep=",")
Output:-
printing the list element using print:
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150, 160, 170, 180, 190, 200]
printing the list element using for loop:
10 20 30 40 50 60 70 80 90 100 110 120 130 140 150 160 170 180 190 200
printing the list element * asterisk:
10 20 30 40 50 60 70 80 90 100 110 120 130 140 150 160 170 180 190 200
printing the list element by comma separator:
[10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150, 160, 170, 180, 190, 200]
D) Code:-
le = [10,20,30,40,50]
print(le)
print(le[1::])
print(le[1:3])
print(le[4:])
print(le[3::])
print(le[::2])
print(le[::4])
print("printing in
reverse") print((le[::-1]))
print(le[-1:-5:-1])
print(le[-3:-5:-1])
print(le[4::])
print(le[::-1])
print(le[::2])
print(le[::4])
Output:-
[10, 20, 30, 40, 50] [20,
30, 40, 50]
[20, 30]
[50]
[40, 50]
[10, 30, 50]
[10, 50]
printing in reverse
[50, 40, 30, 20, 10]
[50, 40, 30, 20]
[30, 20]
[50]
[50, 40, 30, 20, 10]
[10, 30, 50]
[10, 50]
2. Using modules numpy
A) Code:-
import numpy as np
from numpy import*
a=np.array([["Mon",1,2,3,4],["Tue",5,6,7,8],["Wed",9,10,11,12],["Thu",13,14,15,16],["Fri",17,18
,19,20],["Sat",21,22,23,24]])
m = reshape(a,(6,5))
#printing array
print(m,end="")
Output:-
[['Mon' '1' '2' '3' '4']
['Tue' '5' '6' '7' '8']
['Wed' '9' '10' '11' '12']
['Thu' '13' '14' '15' '16']
['Fri' '17' '18' '19' '20']
['Sat' '21' '22' '23' '24']]
B) Code:-
import numpy as np
from numpy import*
a=np.array([["Mon",1,2,3,4],["Tue",5,6,7,8],["Wed",9,10,11,12],["Thu",13,14,15,16],["Fri",17,18
,19,20],["Sat",21,22,23,24]])
m = reshape(a,(6,5))
#printing array
print(m[2])
Output:-
['Wed' '9' '10' '11' '12']
C) Code:-
import numpy as np
from numpy import*
a=np.array([["Mon",1,2,3,4],["Tue",5,6,7,8],["Wed",9,10,11,12],["Thu",13,14,15,16],["Fri",17,18
,19,20],["Sat",21,22,23,24]])
m = reshape(a,(6,5))
#printing array
print(m,end="")
r = append(m,["Sun",25,26,27,28])
print(r)
Output:-
[['Mon' '1' '2' '3' '4']
['Tue' '5' '6' '7' '8']
['Wed' '9' '10' '11' '12']
['Thu' '13' '14' '15' '16']
['Fri' '17' '18' '19' '20']
['Sat' '21' '22' '23' '24']]['Mon' '1' '2' '3' '4' 'Tue' '5' '6' '7' '8' 'Wed' '9' '10' '11' '12'
'Thu' '13' '14' '15' '16' 'Fri' '17' '18' '19' '20' 'Sat' '21' '22' '23'
'24' 'Sun' '25' '26' '27' '28']
D) Code:-
import numpy as np
from numpy import*
a=np.array([["Mon",1,2,3,4],["Tue",5,6,7,8],["Wed",9,10,11,12],["Thu",13,14,15,16],["Fri",17,18
,19,20],["Sat",21,22,23,24]])
m = reshape(a,(6,5))
d = np.delete(m,[3],0)
print(d,end="")
Output:-
[['Mon' '1' '2' '3' '4']
['Tue' '5' '6' '7' '8']
['Wed' '9' '10' '11' '12']
['Fri' '17' '18' '19' '20']
['Sat' '21' '22' '23' '24']]
E) Code:-
import numpy as np
from numpy import*
a=np.array([["Mon",1,2,3,4],["Tue",5,6,7,8],["Wed",9,10,11,12],["Thu",13,14,15,16],["Fri",17,18
,19,20],["Sat",21,22,23,24]])
m = reshape(a,(6,5))
print(m)
#Printing array
r = append(m,["Sun",25,26,27,28])
print(r)
d = np.delete(r,
[3],0) print(d)
print(a[2])
Output:-
[['Mon' '1' '2' '3' '4']
['Tue' '5' '6' '7' '8']
['Wed' '9' '10' '11' '12']
['Thu' '13' '14' '15' '16']
['Fri' '17' '18' '19' '20']
['Sat' '21' '22' '23' '24']]
['Mon' '1' '2' '3' '4' 'Tue' '5' '6' '7' '8' 'Wed' '9' '10' '11' '12'
'Thu' '13' '14' '15' '16' 'Fri' '17' '18' '19' '20' 'Sat' '21' '22' '23'
'24' 'Sun' '25' '26' '27' '28']
['Mon' '1' '2' '4' 'Tue' '5' '6' '7' '8' 'Wed' '9' '10' '11' '12' 'Thu'
'13' '14' '15' '16' 'Fri' '17' '18' '19' '20' 'Sat' '21' '22' '23' '24'
'Sun' '25' '26' '27' '28']
['Wed' '9' '10' '11' '12']
F) Code:-
import numpy as np
from numpy import*
a=np.array([["Mon",1,2,3,4],["Tue",5,6,7,8],["Wed",9,10,11,12],["Thu",13,14,15,16],["Fri",17,18
,19,20],["Sat",21,22,23,24]])
print(a)
a[3] = ["N/a",0,0,0,0]
print(a)
Output:-
[['Mon' '1' '2' '3' '4']
['Tue' '5' '6' '7' '8']
['Wed' '9' '10' '11' '12']
['Thu' '13' '14' '15' '16']
['Fri' '17' '18' '19' '20']
['Sat' '21' '22' '23' '24']]
[['Mon' '1' '2' '3' '4']
['Tue' '5' '6' '7' '8']
['Wed' '9' '10' '11' '12']
['N/a' '0' '0' '0' '0']
['Fri' '17' '18' '19' '20']
['Sat' '21' '22' '23'
'24']]
P
ractical No.02
Q. Write a program to implement Single Linked List with insertion, deletion,
traversal operations.
Code:-
class Node:
def init (self, data, next=None):
self.dataVal = data
self.nextVal = next
class SingleLinkList:
def init (self, head=None):
self.headVal = head
def listprint(self):
printval = self.headVal
while printval is not None:
print(printval.dataVal, end=",
") printval = printval.nextVal
def insertAtBeginning(self,
newdata): NewNode =
Node(newdata) NewNode.nextVal =
self.headVal self.headVal =
NewNode
def insertAtEnd(self,
newdata): NewNode =
Node(newdata)
if self.headVal is None:
self.headVal =
NewNode return
laste = self.headVal
while
laste.nextVal:
laste.nextVal = NewNode
def insertInBetween(self, middle_node,
newdata): if middle_node is None:
print("The mentioned node is
absent") return
NewNode = Node(newdata)
NewNode.nextVal = middle_node.nextVal
middle_node.nextVal = NewNode
def removeNode(self, Removekey):
HeadVal =
self.headVal if
HeadVal is not None:
if HeadVal.dataVal == Removekey:
self.headVal = HeadVal.nextVal
HeadVal
= None
return
while HeadVal is not None:
if HeadVal.dataVal == Removekey: break
prev = HeadVal
HeadVal = HeadVal.nextVal
if HeadVal is None:
return
prev.nextVal =
HeadVal.nextVal HeadVal =
None
def removeStart(self):
if self.headVal is not None:
self.headVal = self.headVal.nextVal
def
removeEnd(self):
last =
self.headVal
if last is None:
print("List is empty")
return
if last.nextVal is None:
self.headVal =
None return None
while last.nextVal.nextVal:
last = last.nextVal
if last.nextVal.nextVal is None:
last.nextVal = None
# Test the corrected
code sli = SingleLinkList()
e1 = Node("Mon")
e2 = Node("Tue")
e3 = Node("Wed")
e4 = Node("Thu")
e5 = Node("Fri")
sli.headVal = e1
e1.nextVal = e2
e2.nextVal = e3
e3.nextVal = e4
e4.nextVal = e5
print("*** Printing Link List
***") sli.listprint()
print("\n*** Printing Link List After Inserting At Beginning
***") sli.insertAtBeginning("Sun")
sli.listprint()
print("\n*** Printing Link List After Inserting At End
***") sli.insertAtEnd("Sat")
sli.listprint()
print("\n*** Printing Link List After Inserting In Between
***") sli.insertInBetween(e3, "n/a")
sli.listprint()
print("\n*** Printing Link List After Removing Element In Between
***")
sli.removeNode("n/a")
sli.listprint()
print("\n*** Printing Link List After Removing Element At Beginning ***")
sli.removeStart()
sli.listprint()
print("\n*** Printing Link List After Removing Element At End
***")
sli.removeEnd()
sli.listprint()
Output:-
*** Printing Link List ***
Mon, Tue, Wed, Thu, Fri,
*** Printing Link List After Inserting At Beginning ***
Sun, Mon, Tue, Wed, Thu, Fri,
*** Printing Link List After Inserting At End ***
Sun, Mon, Tue, Wed, Thu, Fri, Sat,
*** Printing Link List After Inserting In Between
*** Sun, Mon, Tue, Wed, n/a, Thu, Fri, Sat,
*** Printing Link List After Removing Element In Between
*** Sun, Mon, Tue, Wed, Thu, Fri, Sat,
*** Printing Link List After Removing Element At Beginning
*** Mon, Tue, Wed, Thu, Fri, Sat,
*** Printing Link List After Removing Element At End
*** Mon, Tue, Wed, Thu, Fri,
P
ractical No. 03
Q. Write a program to implement a Double Linked list with insertion, deletion,
traversal operations.
Code:-
#node structure
class Node:
# constructor to create a new
node def init (self, data):
self.data = data
self.next = None
self.prev = None
# class Linked
List class
LinkedList:
# constructor to create an empty
LinkedList def init (self):
self.head =
None # test the
code
# create an empty
LinkedList MyList =
LinkedList()
# Add first node.
first = Node(10)
# linking with head node
MyList.head = first
# Add second node.
second = Node(20)
# linking with first node
second.prev = first
first.next =
second # Add third
node. third =
Node(30)
# linking with second node
third.prev = second
second.next = third
# Function to print the linked list def
print_linked_list(linked_list):
current = linked_list.head while
current is not None:
print(current.data, end=" -> ")
current = current.next
print("None")
# Print the linked list
print("Linked List:")
print_linked_list(MyList
Output:-
10 ->; 20 ->; 30 ->; None
P
ractical No.04
Q.4: write a program to implement stack with insertion, deletion,traversal
operations 1.Using list
A) Code:-
stack=[]
stack.append(10) #append method is used to push the
element stack.append(20)
stack.append(300)
print(stack)
stack.pop() #the pop method is used to remove the
element print(stack)
print("no.of element in
stack:-",len(stack)) stack.pop()
stack.pop()
Output:-
[10, 20, 300]
[10, 20]
no.of element in stack:- 2
2. Using modules
A) Code:-
import collections
stack=collections.deque()
stack.append(10)
stack.append(3.14)
stack.append("value of p1")
stack.append("value of
radius") stack.append(10)
stack.append(10)
print(stack)
print("no of element in deque:-",len(stack)) #return the number of items in a
stack print("count 10 in deque:-",stack.count(10))
Output:-
deque([10, 3.14, 'value of p1', 'value od radius', 10,
10]) no of element in deque:- 6
count 10 in deque:- 3
B) Code:-
import queue
stack=queue.LifoQueue()
stack.put(10)
stack.put(200)
stack.put("SYBSCCS
Class")
print("check stack is empty or
not:-",stack.empty()) print("check stack is full or
not:-",stack.full()) print("no.of the item in
lifoqueue:-",stack.qsize())
print("element:-",stack.get())
print("element:-",stack.get())
print("element:-",stack.get())
print("check stack is empty or not:-",stack.empty())
Output:-
check stack is empty or not:-
False check stack is full or not:-
False no.of the item in
lifoqueue:- 3 element:- SYBSCCS
Class
element:- 200
element:- 10
check stack is empty or not:- True
P
ractical No.05
Q.5 : write a program to implement queue with insertion ,deletion ,traversal
operations 1.Using list
A) Code:-
q=[] #right to left
q.append(10)
q.append(20)
q.append(30)
print(q)
print("Length of queue
is:-",len(q)) q.pop(0)
q.pop(0)
print(q)
Output:-
[10, 20, 30]
Length of queue is:- 3
[30]
B) Code:-
q=[] #left to right
q.insert(0,10)
q.insert(0,20)
q.insert(0,30)
print(q)
print("Length of queue
is:-",len(q)) q.pop()
q.pop()
print(q)
Output:-
[30, 20, 10]
Length of queue is:- 3
[30]
2. Using Modules
A) Code:-
import collections
q=collections.deque() #left to right
q.appendleft(10)
q.appendleft(20)
q.appendleft(30)
print(q)
print("No of elements in deque is :-",len(q)) #printing length of stack
print("No.of elements in deque is:-",q.count(10)) #To count the
deque q.pop()
q.pop()
print(q)
Output:-
deque([30, 20, 10])
No of elements in deque is :- 3
No.of elements in deque is:- 1
deque([30])
B) Code:-
import collections
q=collections.deque() #right to left
q.appendleft(10)
q.appendleft(20)
q.appendleft(30)
print(q)
print("No of elements in deque is :-",len(q)) #printing length of stack
print("No.of elements in deque is:-",q.count(10)) #To count the
deque q.popleft()
q.popleft()
print(q)
Output:-
deque([30, 20, 10])
No of elements in deque is :- 3
No.of elements in deque is:- 1
deque([10])
P
ractical No.06
Q.6 write a program to implement Priority queue with insertion, deletion, traversal operations.
A) Code:-
#Increasing
order q=[]
q.append(150)
q.append(300)
q.append(500)
q.append(130)
print("Original Queue:",q)
q.sort()
print("After Sorting:",q)
#Removing the highest priority
element. print("Removed
Element:",q.pop()) print("Queue after
pop:",q)
Output:-
Original Queue: [150, 300, 500, 130]
After Sorting: [130, 150, 300, 500]
Removed Element: 500
Queue after pop: [130, 150, 300]
B) Code:-
#Decreasing
order q=[]
q.append(150)
q.append(300)
q.append(500)
q.append(130)
print("Original Queue:",q)
q.sort(reverse=True)
print("After Sorting:",q)
#Removing the highest priority
element. print("Removed
Element:",q.pop(0)) print("Queue after
pop:",q)
Output:-
Original Queue: [150, 300, 500,
130] After Sorting: [500, 300, 150,
130] Removed Element: 500
Queue after pop: [300, 150, 130]
C) Code:-
#Decreasing
order q=[]
q.append(150)
q.append(300)
q.append(500)
q.append(130)
print("Original Queue:",q)
q.sort(reverse=True)
print("After Sorting:",q)
#Removing the highest priority
element. print("Removed
Element:",q.pop(0))
print("Queue after pop:",q)
q.append(350)
q.append(380)
q.append(800)
q.append(750)
print("Queue Before
Sorting:",q)
q.sort(reverse=True)
print("After Sorting:",q)
#Removing the highest priority
element. print("Removed
Element:",q.pop(0))
Output:-
Original Queue: [150, 300, 500, 130]
After Sorting: [500, 300, 150, 130]
Removed Element: 500
Queue after pop: [300, 150, 130]
Queue Before Sorting: [300, 150, 130, 350, 380, 800,
750] After Sorting: [800, 750, 380, 350, 300, 150, 130]
Removed Element: 800
2. Using module
A) Code:-
import queue
q=queue.PriorityQueue()
q.put(150)
q.put(460)
q.put(20)
q.put(45)
q.put(10)
q.put(34)
q.put(100)
print("Elements in queue:",)
for n in list(q.queue):
print(n,end=" ")
#Removing elements from queue
print("/nRemoved Element:",q.get())
print("Removed Element:",q.get())
print("Removed Element:",q.get())
print("Removed Element:",q.get())
Output:-
Elements in queue:
10 20 34 460 45 150 100
Removed Element: 10
Removed Element: 20
Removed Element: 34
Removed Element: 45
B) Code:-
# node structure
class Node:
def init (self, data):
self.data = data
self.next = None
#class Linked List
class LinkedList:
def init (self):
self.head = None
#Add new element at the start of the
list def push_front(self, newElement):
newNode = Node(newElement)
newNode.next = self.head
self.head = newNode
#display the content of the
list def PrintList(self):
temp = self.head
if(temp != None):
print("The list contains:", end="
") while (temp != None):
print(temp.data, end=" ")
temp = temp.next
print()
else:
print("The list is empty.")
# test the code
MyList =
LinkedList()
#Add three elements at the start of the list.
MyList.push_front(10
MyList.push_front(20
MyList.push_front(30
) MyList.PrintList()
Output:-
The list contains: 30 20 10
P
ractical No.07
Q. Write a program to implement Binary Tree with insertion,deletion,traversal operations
Code:-
class Node:
def init (self,key):
self.left=None
self.right=None
self.val=key
#traverse preorder
def
traversePreOrder(self):
print(self.val,end=' ')
if self.left:
self.left.traversePreOrder()
if self.right:
self.right.traversePreOrder(
) #traverse inorder
def
traverseInOrder(self): if
self.left:
self.left.traverseInOrder(
) print(self.val,end=' ')
if self.right:
self.right.traverseInOrder(
) #Traverse PostOrder
def
traversePostOrder(self): if
self.left:
self.left.traversePostOrder(
)
if self.right:
self.right.traversePostOrder()
print(self.val,end=' ')
root=Node(1)
root.left=Node(2)
root.right=Node(3)
root.left.left=Node(4)
root.left.right=Node(5)
print("pre order
Traversal:",end="")
root.traversePreOrder()
print("\nIn order
Traversal:",end="")
root.traverseInOrder()
print("\nPost order
Traversal:",end="")
root.traversePostOrder()
Output:-
pre order Traversal:1 2 4 5 3
In order Traversal:4 2 5 1 3
Post order Traversal:4 5 2 3 1
P
ractical No.08
Q. Write a program to implement Graph with insertion, deletion, traversal operations.
Code:-
# Graph implementation using
dictionary class Graph:
def init (self, gdict=None):
if gdict is None:
gdict = {}
self.gdict =
gdict
def getVertices(self):
return list(self.gdict.keys())
def getEdges(self):
return
list(self.gdict.values())
graph_element = {
"a": ["b", "c"],
"b": ["a", "d"],
"c": ["a", "d"],
"d": ["b", "c", "e"],
"e": ["d"]
}
g = Graph(graph_element)
print("Representation of graph using
dictionary") print(graph_element)
print("\nKeys:")
print(g.getVertices())
print("\nEdges:")
print(g.getEdges())
Output:-
Representation of graph using dictionary
{'a': ['b', 'c'], 'b': ['a', 'd'], 'c': ['a', 'd'], 'd': ['b', 'c', 'e'], 'e': ['d']}
Keys:
['a', 'b', 'c', 'd', 'e']
Edges:
[['b', 'c'], ['a', 'd'], ['a', 'd'], ['b', 'c', 'e'], ['d']]
P
ractical No.09
Q. Write a program to implement Huffman coding algorithms.
Code:-
# Huffman Coding in python
string = 'BCAADDDCCACACAC'
# Creating tree nodes
class
NodeTree(object):
def init (self, left=None, right=None):
self.left = left
self.right = right
def children(self):
return (self.left, self.right)
def nodes(self):
return (self.left, self.right)
def str (self):
return '%s_%s' % (self.left, self.right)
# Main function implementing huffman coding
def huffman_code_tree(node, left=True,
binString=''): if type(node) is str:
return {node: binString}
(l, r) = node.children()
d = dict()
d.update(huffman_code_tree(l, True, binString +
'0')) d.update(huffman_code_tree(r, False, binString
+ '1')) return d
# Calculating frequency
freq = {}
for c in string:
if c in freq:
freq[c] += 1
else:
freq[c] = 1
freq = sorted(freq.items(), key=lambda x: x[1], reverse=True)
nodes = freq
while len(nodes) > 1:
(key1, c1) = nodes[-
1]
(key2, c2) = nodes[-
2] nodes = nodes[:-2]
node = NodeTree(key1, key2)
nodes.append((node, c1 + c2))
nodes = sorted(nodes, key=lambda x: x[1], reverse=True)
huffmanCode = huffman_code_tree(nodes[0][0])
print(' Char | Huffman code ')
print(' ')
for (char, frequency) in freq:
print(' %-4r |%12s' % (char, huffmanCode[char]))
Output:-
Char | Huffman code
'C' | 0
'A' | 11
'D' | 101
'B' | 100
P
ractical No.10
Q.10 Write a program to create basic Hash Table for insertion, deletion, traversal
operations (assume that there are no collisions)
Code:-
class HashTable1:
def init (self, size):
self.size = size
self.table = [None] * size
def _hash_function(self, key):
return hash(key) % self.size
def insert(self, key, value):
index =
self._hash_function(key)
self.table[index] = (key, value)
def delete(self, key):
index = self._hash_function(key)
if self.table[index] and self.table[index][0] ==
key: self.table[index] = None
def get(self, key):
index = self._hash_function(key)
if self.table[index] and self.table[index][0] ==
key: return self.table[index][1]
else:
return None
def traverse(self):
for item in self.table:
if item:
print(f"Key: {item[0]}, Value: {item[1]}")
# Example usage:
ht = HashTable1(10)
ht.insert("apple", 5)
ht.insert("banana", 10)
ht.insert("cherry", 15)
print("HashTable:"
) ht.traverse()
ht.delete("banana") print("\
nAfter deleting 'banana':")
ht.traverse()
search_result =
ht.get("cherry") if
search_result is not None:
print("\nSearch result for 'cherry':",
search_result) else:
print("\n'cherry' not found in the HashTable.")
Output:-
HashTable:
Key: cherry, Value: 15
Key: apple, Value: 5
Key: banana, Value:
10
After deleting 'banana':
Key: cherry, Value: 15
Key: apple, Value: 5
Search result for 'cherry': 15