10 - Data Structures Design Lab Manual
10 - Data Structures Design Lab Manual
11.Implementation of Heaps
Program No: 1 A
File Name: IMPLEMENTATION OF SIMPLE ABSTRACT
Ex. No: CLASS IN PYTHON
Date: ___________
Aim:
def calculateBill(units):
# Driver Code
units=int(input("Enter number of units:"))
print(“Payable Amount is : ”)
print(calculateBill(units));
Output:
Program No: 1 B
File Name: IMPLEMENTATION OF SIMPLE
ABSTRACT CLASS IN PYTHON
Ex. No:
Date: ___________
Aim:
Program:
class cal():
def __init__(self,a,b):
self.a=a
self.b=b
def add(self):
return self.a+self.b
def mul(self):
return self.a*self.b
def div(self):
return self.a/self.b
def sub(self):
return self.a-self.b
elif choice==3:
print("Result: ",obj.mul())
elif choice==4:
print("Result: ",round(obj.div(),2))
elif choice==0:
print("Exiting!")
else:
print("Invalid choice!!")
print()
Output:
0. Exit
1. Add
2. Subtraction
3. Multiplication
4. Division
Data Structures Design 327
Program No: 2 A
File Name: IMPLEMENTATION OF SIMPLE RECURSIVE
ALGORITHMS IN PYTHON
Ex. No:
Factorial
Date: ___________
Aim:
Program:
def factorial(x):
if x == 1:
return 1
else:
return (x * factorial(x-1))
num = int(input("Enter a number: "))
result = factorial(num)
print("The factorial of", num, "is", result)
Output:
Enter a number: 6
The factorial of 6 is 720
328 Data Structures Design Laboratory
Program No: 2 B
File Name: IMPLEMENTATION OF SIMPLE RECURSIVE
ALGORITHMS IN PYTHON
Ex. No:
Tower of Hanoi
Date: ___________
Aim:
To write a Python program for Tower of Hanoi using recursion.
Program:
Program No: 3A
File Name: IMPLEMENTATION OF LIST USING
Ex. No:
ARRAYS IN PYTHON
Date: ___________
Aim:
Program:
searchByValue(number_array, 9)
print("///////////////searchByValue in an Array ///////////////")
Output:
Program No: 4A
File Name: IMPLEMENTATION OF LINKED LIST INPYTHON
Ex. No:
Date: ___________
Aim:
To write a Python program to create linked list with n elements.
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 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()
332 Data Structures Design Laboratory
Output:
Program No: 4B
File Name: IMPLEMENTATION OF LINKED LIST IN PYTHON
Ex. No:
Date: ___________
Aim:
To write a Python program to search key element in a linked list.
Program:
class Node:
class LinkedList:
def __init__(self):
self.head = None
if __name__ == '__main__':
llist = LinkedList()
llist.push(30);
llist.push(11);
llist.push(21);
llist.push(14);
if llist.search(21):
print("Yes")
else:
print("No")
Output:
Program No: 5A
File Name: IMPLEMENTATION OF STACK IN PYTHON
Ex. No:
Date: ___________
Aim:
To write a Python program to insert elements into stack.
Program:
def create_stack():
stack = []
return stack
def check_empty(stack):
return len(stack) == 0
def push(stack, item):
stack.append(item)
print("pushed item: " + item)
def pop(stack):
if (check_empty(stack)):
return "stack is empty"
return stack.pop()
stack = create_stack()
push(stack, str(1))
push(stack, str(2))
push(stack, str(3))
push(stack, str(4))
print("popped item: " + pop(stack))
print("stack after popping an element: " + str(stack))
Output:
Pushed item: 1
Pushed item: 2
Pushed item: 3
Pushed item: 4
Popped item: 4
Stack after popping an element: [‘1’, ‘2’, ‘3’]
336 Data Structures Design Laboratory
Program No: 5B
File Name: IMPLEMENTATION OF QUEUE IN PYTHON
Ex. No:
Date: ___________
Aim:
To write a Python program to implement queue.
Program:
class Queue:
def __init__(self):
self.queue = []
# Add an element
def enqueue(self, item):
self.queue.append(item)
# Remove an element
def dequeue(self):
if len(self.queue) < 1:
return None
return self.queue.pop(0)
def size(self):
return len(self.queue)
q = Queue()
q.enqueue(1)
q.enqueue(2)
q.enqueue(3)
q.enqueue(4)
q.enqueue(5)
q.display()
q.dequeue()
Data Structures Design 337
Output:
[1, 2, 3, 4, 5]
After removing an element
[2, 3, 4, 5]
338 Data Structures Design Laboratory
Program No: 6A
File Name: APPLICATION OF LIST ADT IN PYTHON
Ex. No:
Card Game
Date: ___________
Aim:
Program:
class Card:
suits = ["spades",
"hearts",
"diamonds",
"clubs"]
return False
return False
def __repr__(self):
v = self.values[self.value] +\
" of " + \
self.suits[self.suit]
return v
class Deck:
def __init__(self):
self.cards = []
for i in range(2, 15):
for j in range(4):
self.cards\
.append(Card(i,
j))
shuffle(self.cards)
def rm_card(self):
if len(self.cards) == 0:
Return
return self.cards.pop()
class Player:
def __init__(self, name):
self.wins = 0
self.card = None
self.name = name
340 Data Structures Design Laboratory
class Game:
def __init__(self):
name1 = input("p1 name ")
name2 = input("p2 name ")
self.deck = Deck()
self.p1 = Player(name1)
self.p2 = Player(name2)
def play_game(self):
cards = self.deck.cards
print("beginning War!")
while len(cards) >= 2:
m = "q to quit. Any " + \
"key to play:"
response = input(m)
if response == 'q':
Break
p1c = self.deck.rm_card()
p2c = self.deck.rm_card()
p1n = self.p1.name
p2n = self.p2.name
self.draw(p1n,
p1c,
p2n,
p2c)
if p1c > p2c:
self.p1.wins += 1
Data Structures Design 341
self.wins(self.p1.name)
else:
self.p2.wins += 1
self.wins(self.p2.name)
win = self.winner(self.p1,
self.p2)
print("War is over.{} wins"
.format(win))
game = Game()
game.play_game()
Output:
p1 name Raja
p2 name Jeon
beginning War!
q to quit. Any key to play:d
Raja drew 10 of spades Jeon drew Ace of hearts
Jeon wins this round
q to quit. Any key to play:7
Raja drew 4 of diamonds Jeon drew 9 of clubs
Jeon wins this round
q to quit. Any key to play:
342 Data Structures Design Laboratory
Program No: 6B
File Name: APPLICATION OF STACK ADT IN PYTHON
Ex. No:
Infix to Postfix Conversion
Date: ___________
Aim:
To write a Python code for infix to postfix conversion
Program:
Operators = set(['+', '-', '*', '/', '(', ')', '^']) # collection of Operators
Priority = {'+':1, '-':1, '*':2, '/':2, '^':3} # dictionary having priorities of Operators
def infixToPostfix(expression):
Output:
Program No: 6C
File Name: APPLICATION OF QUEUE ADT IN PYTHON
Ex. No:
first come first serve scheduling
Date: ___________
Aim:
To write a Python program for first come first serve scheduling program.
Program:
l.append(a)
l.append(b)
d[key] = l
ET = []
for i in range(len(d)):
# first process
if(i==0):
ET.append(d[i][1][1])
TAT = []
for i in range(len(d)):
TAT.append(ET[i] - d[i][1][0])
WT = []
for i in range(len(d)):
WT.append(TAT[i] - d[i][1][1])
avg_WT = 0
for i in WT:
avg_WT +=i
avg_WT = (avg_WT/n)
Output:
Program No: 7A
File Name: IMPLEMENTATION OF LINEAR SEARCHING
Ex. No: TECHNIQUES
Date: ___________
Aim:
To write a Python script for implementing linear search technique.
Program:
list1 = [1 ,3, 5, 4, 7, 9]
print(list1)
n = len(list1)
res = linear_Search(list1, n, key)
if(res == -1):
print("Element not found")
else:
print("Element found at index: ", res)
Output:
[1, 3, 5, 4, 7, 9]
enter the key to search 5
Element found at index: 2
Program No: 7B
File Name: IMPLEMENTATION OF BINARY SEARCHING
Ex. No: TECHNIQUE
Date: ___________
Aim:
Write a Python program to search an element in a given linear list using recursion.
Program:
else:
return binarySearchAppr(arr, mid+1, end, x)
else:
return -1
arr = sorted(['t','u','t','o','r','i','a','l'])
x ='r'
result = binarySearchAppr(arr, 0, len(arr)-1, x)
if result != -1:
print ("Element is present at index "+str(result))
else:
print ("Element is not present in array")
Output:
Element is present at index 4
Program No: 7C
File Name: IMPLEMENTATION OF SORTING TECHNIQUE
Ex. No:
Bubble Sort
Date: ___________
Aim:
To write a Python program to arrange the given elements using bubble sort.
Program:
def bubbleSort(arr):
n = len(arr)
for i in range(n-1):
for j in range(0, n-i-1):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
bubbleSort(arr)
print ("Sorted array is:")
for i in range(len(arr)):
print ("% d" % arr[i],end=" ")
Output:
11 12 22 25 34 64 90
Program No: 7D
File Name: IMPLEMENTATION OF SORTING TECHNIQUE
Ex. No:
Insertion Sort
Date: ___________
Aim:
To write a Python program to arrange the given elements using insertion sort.
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]
350 Data Structures Design Laboratory
j -= 1
arr[j+1] = key
Output:
Program No: 7E
File Name: IMPLEMENTATION OF SORTING TECHNIQUE
Ex. No:
Selection Sort
Date: ___________
Aim:
To write a Python program to arrange the given elements using selection sort.
Program:
import sys
A = [64, 25, 12, 22, 11]
for i in range(len(A)):
min_idx = i
for j in range(i+1, len(A)):
if A[min_idx] > A[j]:
Data Structures Design 351
min_idx = j
A[i], A[min_idx] = A[min_idx], A[i]
Output:
Sorted array
11
22
12
25
64
Program No: 8A
File Name: IMPLEMENTATION HASH TABLE
Ex. No:
Date: ___________
Aim:
To write a Python program to print a binary tree in vertical order.
Program:
def display_hash(hashTable):
for i in range(len(hashTable)):
print(i, end = " ")
for j in hashTable[i]:
print("-->", end = " ")
352 Data Structures Design Laboratory
display_hash (HashTable)
Output:
Program No:9 A
File Name: IMPLEMENTATION TREE REPRESENTATION
Ex. No: AND TRAVERSAL ALGORITHM
Date: ___________
Aim:
To write a Python program for inorder traverse to search element from binary tree.
Program:
class Node:
self.left = None
self.right = None
354 Data Structures Design Laboratory
self.data = data
# Insert Node
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
# Inorder traversal
# Left -> Root -> Right
def inorderTraversal(self, root):
res = []
if root:
res = self.inorderTraversal(root.left)
res.append(root.data)
res = res + self.inorderTraversal(root.right)
return res
root = Node(27)
root.insert(14)
root.insert(35)
root.insert(10)
root.insert(19)
root.insert(31)
Data Structures Design 355
root.insert(42)
print(root.inorderTraversal(root))
Output:
Program No: 9B
File Name: IMPLEMENTATION TREE REPRESENTATION
Ex. No: AND TRAVERSAL ALGORITHM
Date: ___________
Aim:
To write a Python program for preorder traverse to search element from binary
tree.
Program:
class Node:
self.left = None
self.right = None
356 Data Structures Design Laboratory
self.data = data
# Insert Node
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
# Preorder traversal
# Root -> Left ->Right
def PreorderTraversal(self, root):
res = []
if root:
res.append(root.data)
res = res + self.PreorderTraversal(root.left)
res = res + self.PreorderTraversal(root.right)
return res
root = Node(27)
root.insert(14)
root.insert(35)
root.insert(10)
root.insert(19)
root.insert(31)
Data Structures Design 357
root.insert(42)
print(root.PreorderTraversal(root))
Output:
Program No: 9C
File Name: IMPLEMENTATION TREE REPRESENTATION
Ex. No: AND TRAVERSAL ALGORITHM
Date: ___________
Aim:
To write a Python program for postorder traversal to search element from binary
tree.
Program:
class Node:
self.left = None
self.right = None
self.data = data
# Insert Node
def insert(self, data):
358 Data Structures Design Laboratory
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
# Postorder traversal
# Left ->Right -> Root
def PostorderTraversal(self, root):
res = []
if root:
res = self.PostorderTraversal(root.left)
res = res + self.PostorderTraversal(root.right)
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.PostorderTraversal(root))
Data Structures Design 359
Output:
Aim:
To write a Python program to insert element into binary tree and display
inorder vertical order.
Program:
class Node:
def __init__(self, key):
self.left = None
self.right = None
self.val = key
return Node(key)
else:
if root.val == key:
return root
elif root.val < key:
root.right = insert(root.right, key)
else:
root.left = insert(root.left, key)
return root
def inorder(root):
if root:
inorder(root.left)
print(root.val)
inorder(root.right)
r = Node(50)
r = insert(r, 30)
r = insert(r, 20)
r = insert(r, 40)
r = insert(r, 70)
r = insert(r, 60)
r = insert(r, 80)
Output:
20
30
40
50
Data Structures Design 361
60
70
80
Aim:
To write a Python program to search element from binary tree.
Program:
class Node:
def __init__(self,data):
#Assign data to the new node, set left and right children to None
self.data = data;
self.left = None;
self.right = None;
class SearchBinaryTree:
def __init__(self):
362 Data Structures Design Laboratory
else:
if(temp.data == value):
self.flag = True;
return;
bt = SearchBinaryTree();
#Add nodes to the binary tree
bt.root = Node(1);
bt.root.left = Node(2);
bt.root.right = Node(3);
bt.root.left.left = Node(4);
bt.root.right.left = Node(5);
bt.root.right.right = Node(6);
bt.searchNode(bt.root, 5);
if(bt.flag):
print("Element is present in the binary tree");
else:
print("Element is not present in the binary tree");
Output:
Aim:
Program:
import sys
class MinHeap:
self.Heap[0] = -1 * sys.maxsize
self.FRONT = 1
if self.Heap[self.leftChild(pos)] <
self.Heap[self.rightChild(pos)]:
self.swap(pos, self.leftChild(pos))
self.minHeapify(self.leftChild(pos))
current = self.size
def remove(self):
popped = self.Heap[self.FRONT]
self.Heap[self.FRONT] = self.Heap[self.size]
self.size-= 1
self.minHeapify(self.FRONT)
return popped
# Driver Code
if __name__ == "__main__":
minHeap.Print()
print("The Min val is " + str(minHeap.remove()))
Output:
The minHeap is
PARENT : 3 LEFT CHILD : 5 RIGHT CHILD : 6
PARENT : 5 LEFT CHILD : 9 RIGHT CHILD : 84
PARENT : 6 LEFT CHILD : 19 RIGHT CHILD : 17
PARENT : 9 LEFT CHILD : 22 RIGHT CHILD : 10
The Min val is 3
Data Structures Design 367
Program:
import sys
class MaxHeap:
self.maxsize = maxsize
self.size = 0
self.Heap = [0] * (self.maxsize + 1)
368 Data Structures Design Laboratory
self.Heap[0] = sys.maxsize
self.FRONT = 1
return pos // 2
return 2 * pos
return (2 * pos) + 1
self.Heap[fpos])
current = self.size
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__":
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
PARENT : 84 LEFT CHILD : 22 RIGHT CHILD : 19
PARENT : 22 LEFT CHILD : 17 RIGHT CHILD : 10
PARENT : 19 LEFT CHILD : 5 RIGHT CHILD : 6
PARENT : 17 LEFT CHILD : 3 RIGHT CHILD : 9
The Max val is 84
Data Structures Design 371
Program:
class Graph(object):
self.size = size
# Add edges
def add_edge(self, v1, v2):
if v1 == v2:
print("Same vertex %d and %d" % (v1, v2))
self.adjMatrix[v1][v2] = 1
self.adjMatrix[v2][v1] = 1
# Remove edges
def remove_edge(self, v1, v2):
if self.adjMatrix[v1][v2] == 0:
print("No edge between %d and %d" % (v1, v2))
return
self.adjMatrix[v1][v2] = 0
self.adjMatrix[v2][v1] = 0
def __len__(self):
return self.size
def main():
g = Graph(5)
g.add_edge(0, 1)
g.add_edge(0, 2)
g.add_edge(1, 2)
g.add_edge(2, 0)
g.add_edge(2, 3)
g.print_matrix()
if __name__ == '__main__':
main()
Output:
Data Structures Design 373
Program:
class AdjNode:
def __init__(self, value):
self.vertex = value
self.next = None
class Graph:
def __init__(self, num):
374 Data Structures Design Laboratory
self.V = num
self.graph = [None] * self.V
# Add edges
def add_edge(self, s, d):
node = AdjNode(d)
node.next = self.graph[s]
self.graph[s] = node
node = AdjNode(s)
node.next = self.graph[d]
self.graph[d] = node
if __name__ == "__main__":
V=5
graph.print_agraph()
Output:
Vertex 3: -> 0
Vertex 4:
Program:
class Graph:
# Constructor
376 Data Structures Design Laboratory
def __init__(self):
# Driver code
Output:
Program:
graph = {
'5' : ['3','7'],
'3' : ['2', '4'],
'7' : ['8'],
'2' : [],
'4' : ['8'],
'8' : []
}
visited = [] # List for visited nodes.
queue = [] #Initialize a queue
378 Data Structures Design Laboratory
Output:
Aim: Write a Python program for single source shortest path using Bellman Ford
Algorithm.
Program:
class Graph:
def __init__(self, vertices):
self.M = vertices # Total number of vertices in the graph
self.graph = [] # Array of edges
# Add edges
self.print_solution(distance)
g = Graph(5)
g.add_edge(0, 1, 2)
g.add_edge(0, 2, 4)
g.add_edge(1, 3, 2)
g.add_edge(2, 4, 3)
g.add_edge(2, 3, 4)
g.add_edge(4, 3, -5)
g.bellman_ford(0)
Output:
Aim: Write a Python program for single source shortest path using Dijiktra’s
Algorithm.
Program:
return min_index
self.printSolution(dist)
# Driver program
g = Graph(9)
g.graph = [[0, 4, 0, 0, 0, 0, 0, 8, 0],
[4, 0, 8, 0, 0, 0, 0, 11, 0],
[0, 8, 0, 7, 0, 4, 0, 0, 2],
[0, 0, 7, 0, 9, 14, 0, 0, 0],
[0, 0, 0, 9, 0, 10, 0, 0, 0],
[0, 0, 4, 14, 10, 0, 2, 0, 0],
[0, 0, 0, 0, 0, 2, 0, 1, 6],
[8, 11, 0, 0, 0, 0, 1, 0, 7],
[0, 0, 2, 0, 0, 0, 6, 7, 0]
]
g.dijkstra(0)
Output:
Aim: Write a Python program to find minimum spanning tree from a given graph
using Prim’s algorithm.
Program:
class Graph():
for v in range(self.V):
if key[v] < min and mstSet[v] == False:
min = key[v]
min_index = v
return min_index
self.printMST(parent)
g = Graph(5)
g.graph = [ [0, 2, 0, 6, 0],
[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
386 Data Structures Design Laboratory
Aim: Write a Python program to find minimum spanning tree from a given graph
using Krushkal algorithm.
Program:
class Graph:
parent = []
rank = []
minimumCost = 0
print ("Edges in the constructed MST")
for u, v, weight in result:
minimumCost += weight
print("%d -- %d == %d" % (u, v, weight))
print("Minimum Spanning Tree" , minimumCost)
# Driver code
g = Graph(4)
Data Structures Design 389
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)
# Function call
g.KruskalMST()
Output: