You are on page 1of 67

List of Programs

1. Implement simple ADTs as Python classes

2. Implement recursive algorithms in Python

3. Implement List ADT using Python arrays

4. Linked list implementations of List

5. Implementation of Stack and Queue ADTs

6. Applications of List, Stack and Queue ADTs

7. Implementation of sorting and searching algorithms

8. Implementation of Hash tables

9. Tree representation and traversal algorithms

10.Implementation of Binary Search Trees

11.Implementation of Heaps

12.Graph representation and Traversal algorithms

13.Implementation of single source shortest path algorithm


324 Data Structures Design Laboratory

14.Implementation of minimum spanning tree algorithms

Program No: 1 A
File Name: IMPLEMENTATION OF SIMPLE ABSTRACT
Ex. No: CLASS IN PYTHON
Date: ___________

Aim:

Write a Python program to calculate electricity bill for a given tariff.

 1 to 100 units – Rs. 10


 100 to 200 units – Rs. 15
 200 to 300 units – Rs.20
 above 300 units – Rs. 25
Program:

def calculateBill(units):

if (units <= 100):


return units * 10;
elif (units <= 200):
return ((100 * 10) + (units - 100) * 15);
elif (units <= 300):
return ((100 * 10) + (100 * 15) + (units - 200) * 20);
elif (units > 300):
return ((100 * 10) + (100 * 15) + (100 * 20) + (units - 300) * 25);
return 0;

# Driver Code
units=int(input("Enter number of units:"))

print(“Payable Amount is : ”)
print(calculateBill(units));

Output:

Enter number of units:320


Payable Amount is :
5000
Data Structures Design 325

Program No: 1 B
File Name: IMPLEMENTATION OF SIMPLE
ABSTRACT CLASS IN PYTHON
Ex. No:
Date: ___________

Aim:

To write a Python program for basic operations of calculator.

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

a=int(input("Enter first number: "))


b=int(input("Enter second number: "))
obj=cal(a,b)
choice=1
while choice!=0:
print("0. Exit")
print("1. Add")
print("2. Subtraction")
print("3. Multiplication")
print("4. Division")
choice=int(input("Enter choice: "))
if choice==1:
print("Result: ",obj.add())
elif choice==2:
print("Result: ",obj.sub())
326 Data Structures Design Laboratory

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:

Enter first number: 25


Enter second number: 5
0. Exit
1. Add
2. Subtraction
3. Multiplication
4. Division
Enter choice: 4
Result: 5.0

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:

Write a Python program to find factorial calculation using recursion.

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:

def tower_of_hanoi(disks, source, auxiliary, target):


if(disks == 1):
print('Move disk 1 from rod {} to rod {}.'.format(source, target))
return
tower_of_hanoi(disks - 1, source, target, auxiliary)
print('Move disk {} from rod {} to rod {}.'.format(disks, source, target))
tower_of_hanoi(disks - 1, auxiliary, source, target)
disks = int(input('Enter the number of disks: '))
tower_of_hanoi(disks, 'A', 'B', 'C')
Output:

Enter the number of disks: 3


Move disk 1 from rod A to rod C.
Move disk 2 from rod A to rod B.
Move disk 1 from rod C to rod B.
Move disk 3 from rod A to rod C.
Move disk 1 from rod B to rod A.
Move disk 2 from rod B to rod C.
Move disk 1 from rod A to rod C.
Data Structures Design 329

Program No: 3A
File Name: IMPLEMENTATION OF LIST USING
Ex. No:
ARRAYS IN PYTHON
Date: ___________

Aim:

To write a Python program to search element in a list using arrays.

Program:

def SearchByIndex(array_val, index_val) :


item_index= index_val;
n = len(array_val);
search_index = 0;
search_value = 'undefined';
while( search_index < n) :
if( search_index == item_index ) :
search_value = array_val[search_index]
break;
search_index = search_index + 1;
return search_value;

def searchByValue(array_val, item) :


n = len(array_val);
search_value = item;
array_index = 0
search_index= 'undefined';
while( array_index < n ) :
if( array_val[array_index] == search_value ):
search_index = array_index
break;
array_index = array_index + 1;
return search_index;
print("///////////////searchByIndex in an Array ////////////////")
number_array = [4, 5, 2, 7, 9, 13];
print("=========== Original Array =========")
for idex, item in enumerate(number_array):
330 Data Structures Design Laboratory

print(" Array [", idex , "] ", item)

print("Array Item '", item , "' is in the position ", searchByValue(number_array,


13))

searchByValue(number_array, 9)
print("///////////////searchByValue in an Array ///////////////")

string_array = ["start", "to", "study", "from", "basics"];


print("=========== Original Array =========")
for idex, item in enumerate(string_array):
print(" Array [", idex , "] ", item)
print("Array Item '", item ,"' is in the position ", searchByValue(string_array,
"basics")) # search by index

Output:

///////////////searchByIndex in an Array ////////////////

=========== Original Array =========


Array [ 0 ] 4
Array [ 1 ] 5
Array [ 2 ] 2
Array [ 3 ] 7
Array [ 4 ] 9
Array [ 5 ] 13
Array Item ' 13 ' is in the position 5

///////////////searchByValue in an Array ///////////////

=========== Original Array =========


Array [ 0 ] start
Array [ 1 ] to
Array [ 2 ] study
Array [ 3 ] from
Array [ 4 ] basics
Array Item ' basics ' is in the position 4
Data Structures Design 331

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 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()
332 Data Structures Design Laboratory

Output:

How many elements would you like to add? 5


Enter data item: 10
Enter data item: 20
Enter data item: 30
Enter data item: 40
Enter data item: 50
The linked list: 10 20 30 40 50
Data Structures Design 333

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:

def ___init__(self, data):


self.data = data
self.next = None

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

def push(self, new_data):


new_node = Node(new_data)
new_node.next = self.head
self.head = new_node

def search(self, x):


current = self.head
while current != None:
if current.data == x:
return True
current = current.next
return False

if __name__ == '__main__':

llist = LinkedList()

# Use push() to construct list


# 14->21->11->30->10
llist.push(10);
334 Data Structures Design Laboratory

llist.push(30);
llist.push(11);
llist.push(21);
llist.push(14);

if llist.search(21):
print("Yes")
else:
print("No")

Output:

Enter element to search: 20


Yes
Data Structures Design 335

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)

# Display the queue


def display(self):
print(self.queue)

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

print("After removing an element")


q.display()

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:

To write a Python program for card of game in Python in List ADT

Program:

from random import shuffle

class Card:
suits = ["spades",
"hearts",
"diamonds",
"clubs"]

values = [None, None,"2", "3",


"4", "5", "6", "7",
"8", "9", "10",
"Jack", "Queen",
"King", "Ace"]

def __init__(self, v, s):


"""suit + value are ints"""
self.value = v
self.suit = s

def __lt__(self, c2):


if self.value < c2.value:
return True
if self.value == c2.value:
if self.suit < c2.suit:
return True
else:
Data Structures Design 339

return False
return False

def __gt__(self, c2):


if self.value > c2.value:
return True
if self.value == c2.value:
if self.suit > c2.suit:
return True
else:
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 wins(self, winner):


w = "{} wins this round"
w = w.format(winner)
print(w)

def draw(self, p1n, p1c, p2n, p2c):


d = "{} drew {} {} drew {}"
d = d.format(p1n,
p1c,
p2n,
p2c)
print(d)

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))

def winner(self, p1, p2):


if p1.wins > p2.wins:
return p1.name
if p1.wins < p2.wins:
return p2.name
return "It was a tie!"

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):

stack = [] # initialization of empty stack


output = ''

for character in expression:


Data Structures Design 343

if character not in Operators: # if an operand append in postfix expression


output+= character
elif character=='(': # else Operators push onto stack
stack.append('(')
elif character==')':
while stack and stack[-1]!= '(':
output+=stack.pop()
stack.pop()
else:
while stack and stack[-1]!='(' and Priority[character]<=Priority[stack[-1]]:
output+=stack.pop()
stack.append(character)
while stack:
output+=stack.pop()
return output

expression = input('Enter infix expression ')


print('infix notation: ',expression)
print('postfix notation: ',infixToPostfix(expression))

Output:

Enter infix expression a+b*c^d-e^f+g*h-i


infix notation: a+b*c^d-e^f+g*h-i
postfix notation: abcd^*+ef^-gh*+i-
344 Data Structures Design Laboratory

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:

print("FIRST COME FIRST SERVE SCHEDULLING")


n= int(input("Enter number of processes : "))
d = dict()
for i in range(n):
key = "P"+str(i+1)
a = int(input("Enter arrival time of process"+str(i+1)+": "))
b = int(input("Enter burst time of process"+str(i+1)+": "))
l = []
Data Structures Design 345

l.append(a)
l.append(b)
d[key] = l

d = sorted(d.items(), key=lambda item: item[1][0])

ET = []
for i in range(len(d)):
# first process
if(i==0):
ET.append(d[i][1][1])

# get prevET + newBT


else:
ET.append(ET[i-1] + 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)

print("Process | Arrival | Burst | Exit | Turn Around | Wait |")


for i in range(n):
print(" ",d[i][0]," | ",d[i][1][0]," | ",d[i][1][1]," | ",ET[i]," | ",TAT[i]," |
",WT[i]," | ")
print("Average Waiting Time: ",avg_WT)

Output:

FIRST COME FIRST SERVE SCHEDULLING


Enter number of processes : 4
Enter arrival time of process1: 5
Enter burst time of process1: 2
346 Data Structures Design Laboratory

Enter arrival time of process2: 4


Enter burst time of process2: 3
Enter arrival time of process3: 3
Enter burst time of process3: 1
Enter arrival time of process4: 3
Enter burst time of process4: 2
Process | Arrival | Burst | Exit | Turn Around | Wait |
P3 | 3 | 1 | 1 | -2 | -3 |
P4 | 3 | 2 | 3 | 0 | -2 |
P2 | 4 | 3 | 6 | 2 | -1 |
P1 | 5 | 2 | 8 | 3 | 1 |
Average Waiting Time: -1.25

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:

def linear_Search(list1, n, key):

# Searching list1 sequentially


for i in range(0, n):
if (list1[i] == key):
return i
return -1
Data Structures Design 347

list1 = [1 ,3, 5, 4, 7, 9]

print(list1)

key = int(input("enter the key to search "))

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:

def binarySearchAppr (arr, start, end, x):


if end >= start:
mid = start + (end- start)//2
if arr[mid] == x:
return mid
elif arr[mid] > x:
return binarySearchAppr(arr, start, mid-1, x)
348 Data Structures Design Laboratory

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]

arr = [64, 34, 25, 12, 22, 11, 90]


Data Structures Design 349

bubbleSort(arr)
print ("Sorted array is:")
for i in range(len(arr)):
print ("% d" % arr[i],end=" ")

Output:

Sorted array is:

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

arr = [12, 11, 13, 5, 6]


insertionSort(arr)
print ("Sorted array is:")
for i in range(len(arr)):
print ("%d" %arr[i])

Output:

Sorted array is:


5
6
11
12
13

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]

print ("Sorted array")


for i in range(len(A)):
print("%d" %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

print(j, end = " ")


print()

HashTable = [[] for _ in range(10)]


def Hashing(keyvalue):
return keyvalue % len(HashTable)
def insert(Hashtable, keyvalue, value):
hash_key = Hashing(keyvalue)
Hashtable[hash_key].append(value)

insert(HashTable, 10, 'Allahabad')


insert(HashTable, 25, 'Mumbai')
insert(HashTable, 20, 'Mathura')
insert(HashTable, 9, 'Delhi')
insert(HashTable, 21, 'Punjab')
insert(HashTable, 21, 'Noida')

display_hash (HashTable)

Output:

0 --> Allahabad --> Mathura


1 --> Punjab --> Noida
2
3
4
5 --> Mumbai
6
7
8
9 --> Delhi
Data Structures Design 353

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:

def __init__(self, data):

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

# Print the Tree


def PrintTree(self):
if self.left:
self.left.PrintTree()
print( self.data),
if self.right:
self.right.PrintTree()

# 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:

[10, 14, 19, 27, 31, 35, 42]

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:

def __init__(self, data):

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

# Print the Tree


def PrintTree(self):
if self.left:
self.left.PrintTree()
print( self.data),
if self.right:
self.right.PrintTree()

# 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:

[27, 14, 10, 19, 35, 31, 42]

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:

def __init__(self, data):

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

# Print the Tree


def PrintTree(self):
if self.left:
self.left.PrintTree()
print( self.data),
if self.right:
self.right.PrintTree()

# 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:

[10, 19, 14, 31, 42, 35, 27]

Program No: 10A


File Name: IMPLEMENTATION BINARY SEARCH TREE
Ex. No:
Date: ___________

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

def insert(root, key):


if root is None:
360 Data Structures Design Laboratory

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)

# Driver program to test the above functions


# Let us create the following BST
# 50
#/ \
# 30 70
#/\/\
# 20 40 60 80

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)

# Print inoder traversal of the BST


inorder(r)

Output:

20
30
40
50
Data Structures Design 361

60
70
80

Program No: 10B


File Name: IMPLEMENTATION BINARY SEARCH TREE
Ex. No:
Date: ___________

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

#Represent the root of binary tree


self.root = None;
self.flag = False;

def searchNode(self, temp, value):


#Check whether tree is empty
if(self.root == None):
print("Tree is empty");

else:
if(temp.data == value):
self.flag = True;
return;

#Search in left subtree


if(self.flag == False and temp.left != None):
self.searchNode(temp.left, value);

#Search in right subtree


if(self.flag == False and temp.right != None):
self.searchNode(temp.right, value);

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);

print("Search for node 5 in the binary tree")

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:

Search for node 5 in the binary tree


Data Structures Design 363

Element is present in the binary tree

Program No: 11A


File Name: IMPLEMENTATION OF MIN HEAP
Ex. No:
Date: ___________

Aim:

To write a Python program to find min heap.

Program:

import sys

class MinHeap:

def __init__(self, maxsize):


self.maxsize = maxsize
self.size = 0
self.Heap = [0]*(self.maxsize + 1)
364 Data Structures Design Laboratory

self.Heap[0] = -1 * sys.maxsize
self.FRONT = 1

# Function to return the position of


# parent for the node currently
# at pos
def parent(self, pos):
return pos//2

# Function to return the position of


# the left child for the node currently
# at pos
def leftChild(self, pos):
return 2 * pos

# Function to return the position of


# the right child for the node currently
# at pos
def rightChild(self, pos):
return (2 * pos) + 1

# Function that returns true if the passed


# node is a leaf node
def isLeaf(self, pos):
return pos*2 > self.size

# Function to swap two nodes of the heap


def swap(self, fpos, spos):
self.Heap[fpos], self.Heap[spos] = self.Heap[spos], self.Heap[fpos]

# Function to heapify the node at pos


def minHeapify(self, pos):

# If the node is a non-leaf node and greater


# than any of its child
if not self.isLeaf(pos):
if (self.Heap[pos] > self.Heap[self.leftChild(pos)] or
self.Heap[pos] > self.Heap[self.rightChild(pos)]):

# Swap with the left child and heapify


# the left child
Data Structures Design 365

if self.Heap[self.leftChild(pos)] <
self.Heap[self.rightChild(pos)]:
self.swap(pos, self.leftChild(pos))
self.minHeapify(self.leftChild(pos))

# Swap with the right child and heapify


# the right child
else:
self.swap(pos, self.rightChild(pos))
self.minHeapify(self.rightChild(pos))

# Function to insert a node into the heap


def insert(self, element):
if self.size >= self.maxsize :
return
self.size+= 1
self.Heap[self.size] = element

current = self.size

while self.Heap[current] < self.Heap[self.parent(current)]:


self.swap(current, self.parent(current))
current = self.parent(current)

# Function to print the contents of the heap


def Print(self):
for i in range(1, (self.size//2)+1):
print(" PARENT : "+ str(self.Heap[i])+" LEFT CHILD : "+
str(self.Heap[2 * i])+"
RIGHT CHILD : "+
str(self.Heap[2 * i + 1]))

# Function to build the min heap using


# the minHeapify function
def minHeap(self):

for pos in range(self.size//2, 0, -1):


self.minHeapify(pos)

# Function to remove and return the minimum


# element from the heap
366 Data Structures Design Laboratory

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__":

print('The minHeap is ')


minHeap = MinHeap(15)
minHeap.insert(5)
minHeap.insert(3)
minHeap.insert(17)
minHeap.insert(10)
minHeap.insert(84)
minHeap.insert(19)
minHeap.insert(6)
minHeap.insert(22)
minHeap.insert(9)
minHeap.minHeap()

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 No: 11B


File Name: IMPLEMENTATION OF MAX HEAP
Ex. No:
Date: ___________

Aim: Write a Python program to implement max heap.

Program:

import sys

class MaxHeap:

def __init__(self, maxsize):

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

# Function to return the position of


# parent for the node currently
# at pos
def parent(self, pos):

return pos // 2

# Function to return the position of


# the left child for the node currently
# at pos
def leftChild(self, pos):

return 2 * pos

# Function to return the position of


# the right child for the node currently
# at pos
def rightChild(self, pos):

return (2 * pos) + 1

# Function that returns true if the passed


# node is a leaf node
def isLeaf(self, pos):

if pos >= (self.size//2) and pos <= self.size:


return True
return False

# Function to swap two nodes of the heap


def swap(self, fpos, spos):

self.Heap[fpos], self.Heap[spos] = (self.Heap[spos],

self.Heap[fpos])

# Function to heapify the node at pos


def maxHeapify(self, pos):
Data Structures Design 369

# If the node is a non-leaf node and smaller


# than any of its child
if not self.isLeaf(pos):
if (self.Heap[pos] < self.Heap[self.leftChild(pos)] or
self.Heap[pos] < self.Heap[self.rightChild(pos)]):

# Swap with the left child and heapify


# the left child
if (self.Heap[self.leftChild(pos)] >
self.Heap[self.rightChild(pos)]):
self.swap(pos, self.leftChild(pos))
self.maxHeapify(self.leftChild(pos))

# Swap with the right child and heapify


# the right child
else:
self.swap(pos, self.rightChild(pos))
self.maxHeapify(self.rightChild(pos))

# Function to insert a node into the heap


def insert(self, element):

if self.size >= self.maxsize:


return
self.size += 1
self.Heap[self.size] = element

current = self.size

while (self.Heap[current] >


self.Heap[self.parent(current)]):
self.swap(current, self.parent(current))
current = self.parent(current)

# Function to print the contents of the heap


def Print(self):

for i in range(1, (self.size // 2) + 1):


print(" PARENT : " + str(self.Heap[i]) +
" LEFT CHILD : " + str(self.Heap[2 * i]) +
" RIGHT CHILD : " + str(self.Heap[2 * i + 1]))
370 Data Structures Design Laboratory

# Function to remove and return the maximum


# element from the heap
def extractMax(self):

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__":

print('The maxHeap is ')

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()

print("The Max val is " + str(maxHeap.extractMax()))

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 No: 12A


File Name: GRAPH REPRESENTATION AND TRAVERSAL
Ex. No:
Adjacency Matrix representation
Date: ___________

Aim: Write a Python program to create and represent nodes in graph.

Program:

# Adjacency Matrix representation in Python

class Graph(object):

# Initialize the matrix


def __init__(self, size):
self.adjMatrix = []
for i in range(size):
self.adjMatrix.append([0 for i in range(size)])
372 Data Structures Design Laboratory

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

# Print the matrix


def print_matrix(self):
for row in self.adjMatrix:
for val in row:
print('{:4}'.format(val)),
print

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 No: 12B


File Name: GRAPH REPRESENTATION AND TRAVERSAL
Ex. No:
Adjacency List representation
Date: ___________

Aim: Write a Python program to represent graph using adjacency list.

Program:

# Adjascency List representation in Python

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

# Print the graph


def print_agraph(self):
for i in range(self.V):
print("Vertex " + str(i) + ":", end="")
temp = self.graph[i]
while temp:
print(" -> {}".format(temp.vertex), end="")
temp = temp.next
print(" \n")

if __name__ == "__main__":
V=5

# Create graph and edges


graph = Graph(V)
graph.add_edge(0, 1)
graph.add_edge(0, 2)
graph.add_edge(0, 3)
graph.add_edge(1, 2)

graph.print_agraph()

Output:

Vertex 0: -> 3 -> 2 -> 1


Vertex 1: -> 2 -> 0
Vertex 2: -> 1 -> 0
Data Structures Design 375

Vertex 3: -> 0
Vertex 4:

Program No: 12C


File Name: DEPTH FIRST TRAVERSAL
Ex. No:
Date: ___________

Aim: Write a Python program to traverse a graph using DFS.

Program:

# Python3 program to print DFS traversal


# from a given graph
from collections import defaultdict

# This class represents a directed graph using


# adjacency list representation

class Graph:

# Constructor
376 Data Structures Design Laboratory

def __init__(self):

# default dictionary to store graph


self.graph = defaultdict(list)

# function to add an edge to graph


def addEdge(self, u, v):
self.graph[u].append(v)

# A function used by DFS


def DFSUtil(self, v, visited):

# Mark the current node as visited


# and print it
visited.add(v)
print(v, end=' ')

# Recur for all the vertices


# adjacent to this vertex
for neighbour in self.graph[v]:
if neighbour not in visited:
self.DFSUtil(neighbour, visited)

# The function to do DFS traversal. It uses


# recursive DFSUtil()
def DFS(self, v):

# Create a set to store visited vertices


visited = set()

# Call the recursive helper function


# to print DFS traversal
self.DFSUtil(v, visited)

# Driver code

# Create a graph given


# in the above diagram
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)
Data Structures Design 377

print("Following is DFS from (starting from vertex 2)")


g.DFS(2)

Output:

Program No: 12D


File Name: BREADTH FIRST TRAVERSAL
Ex. No:
Date: ___________

Aim: Write a Python program to traverse a graph using BFS.

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

def bfs(visited, graph, node): #function for BFS


visited.append(node)
queue.append(node)
while queue: # Creating loop to visit each node
m = queue.pop(0)
print (m, end = " ")
for neighbour in graph[m]:
if neighbour not in visited:
visited.append(neighbour)
queue.append(neighbour)
# Driver Code
print("Following is the Breadth-First Search")
bfs(visited, graph, '5') # function calling

Output:

Following is the Breadth-First Search


5 3 7 2 4 8

Program No: 13A


File Name: SINGLE SOURCE SHORTEST PATH ALGORITHM
Ex. No: Bellman Ford Algorithm
Date: ___________

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

def add_edge(self, a, b, c):


self.graph.append([a, b, c])
Data Structures Design 379

# Print the solution


def print_solution(self, distance):
print("Vertex Distance from Source")
for k in range(self.M):
print("{0}\t\t{1}".format(k, distance[k]))

def bellman_ford(self, src):


distance = [float("Inf")] * self.M
distance[src] = 0
for _ in range(self.M - 1):
for a, b, c in self.graph:
if distance[a] != float("Inf") and distance[a] + c < distance[b]:
distance[b] = distance[a] + c
for a, b, c in self.graph:
if distance[a] != float("Inf") and distance[a] + c < distance[b]:
print("Graph contains negative weight cycle")
return

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:

Vertex Distance from Source


0 0
1 2
2 4
3 2
4 7
380 Data Structures Design Laboratory

Program No: 13B


File Name: SINGLE SOURCE SHORTEST PATH ALGORITHM
Ex. No: Dijiktra’s Algorithm.
Date: ___________

Aim: Write a Python program for single source shortest path using Dijiktra’s
Algorithm.

Program:

# Python program for Dijkstra's single


# source shortest path algorithm. The program is
# for adjacency matrix representation of the graph
class Graph():

def __init__(self, vertices):


self.V = vertices
self.graph = [[0 for column in range(vertices)]
for row in range(vertices)]
Data Structures Design 381

def printSolution(self, dist):


print("Vertex \t Distance from Source")
for node in range(self.V):
print(node, "\t\t", dist[node])

# A utility function to find the vertex with


# minimum distance value, from the set of vertices
# not yet included in shortest path tree
def minDistance(self, dist, sptSet):

# Initialize minimum distance for next node


min = 1e7

# Search not nearest vertex not in the


# shortest path tree
for v in range(self.V):
if dist[v] < min and sptSet[v] == False:
min = dist[v]
min_index = v

return min_index

# Function that implements Dijkstra's single source


# shortest path algorithm for a graph represented
# using adjacency matrix representation
def dijkstra(self, src):

dist = [1e7] * self.V


dist[src] = 0
sptSet = [False] * self.V

for cout in range(self.V):

# Pick the minimum distance vertex from


# the set of vertices not yet processed.
# u is always equal to src in first iteration
u = self.minDistance(dist, sptSet)

# Put the minimum distance vertex in the


# shortest path tree
sptSet[u] = True
382 Data Structures Design Laboratory

# Update dist value of the adjacent vertices


# of the picked vertex only if the current
# distance is greater than new distance and
# the vertex in not in the shortest path tree
for v in range(self.V):
if (self.graph[u][v] > 0 and
sptSet[v] == False and
dist[v] > dist[u] + self.graph[u][v]):
dist[v] = dist[u] + self.graph[u][v]

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:

Vertex Distance from Source


0 0
1 4
2 12
3 19
4 21
5 11
6 9
7 8
8 14
Data Structures Design 383

Program No: 14A


File Name: IMPLEMENTATION OF MINIMUM SPANNING
TREE
Ex. No:
Prim’s algorithm
Date: ___________

Aim: Write a Python program to find minimum spanning tree from a given graph
using Prim’s algorithm.

Program:

# A Python program for Prim's Minimum Spanning Tree (MST) algorithm.


# The program is for adjacency matrix representation of the graph

import sys # Library for INT_MAX

class Graph():

def __init__(self, vertices):


self.V = vertices
self.graph = [[0 for column in range(vertices)]
for row in range(vertices)]
384 Data Structures Design Laboratory

# A utility function to print the constructed MST stored in parent[]


def printMST(self, parent):
print ("Edge \tWeight")
for i in range(1, self.V):
print (parent[i], "-", i, "\t", self.graph[i][parent[i]])

# A utility function to find the vertex with


# minimum distance value, from the set of vertices
# not yet included in shortest path tree
def minKey(self, key, mstSet):

# Initialize min value


min = sys.maxsize

for v in range(self.V):
if key[v] < min and mstSet[v] == False:
min = key[v]
min_index = v
return min_index

# Function to construct and print MST for a graph


# represented using adjacency matrix representation
def primMST(self):

# Key values used to pick minimum weight edge in cut


key = [sys.maxsize] * self.V
parent = [None] * self.V # Array to store constructed MST
# Make key 0 so that this vertex is picked as first vertex
key[0] = 0
mstSet = [False] * self.V

parent[0] = -1 # First node is always the root of

for cout in range(self.V):

# Pick the minimum distance vertex from


# the set of vertices not yet processed.
# u is always equal to src in first iteration
u = self.minKey(key, mstSet)

# Put the minimum distance vertex in


# the shortest path tree
mstSet[u] = True

# Update dist value of the adjacent vertices


# of the picked vertex only if the current
Data Structures Design 385

# distance is greater than new distance and


# the vertex in not in the shortest path tree
for v in range(self.V):

# graph[u][v] is non zero only for adjacent vertices of m


# mstSet[v] is false for vertices not yet included in MST
# Update the key only if graph[u][v] is smaller than key[v]

if self.graph[u][v] > 0 and mstSet[v] == False and key[v] > self.graph[u][v]:


key[v] = self.graph[u][v]
parent[v] = u

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

Program No: 14A


File Name: IMPLEMENTATION OF MINIMUM SPANNING
TREE
Ex. No:
Date: ___________

Program No: 14B


File Name: IMPLEMENTATION OF MINIMUM SPANNING
TREE
Ex. No:
Krushkal’s algorithm
Date: ___________

Aim: Write a Python program to find minimum spanning tree from a given graph
using Krushkal algorithm.

Program:

from collections import defaultdict

class Graph:

def __init__(self, vertices):


self.V = vertices # No. of vertices
self.graph = [] # default dictionary
# to store graph

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


self.graph.append([u, v, w])
Data Structures Design 387

# A utility function to find set of an element i


# (uses path compression technique)
def find(self, parent, i):
if parent[i] == i:
return i
return self.find(parent, parent[i])

# A function that does union of two sets of x and y


# (uses union by rank)
def union(self, parent, rank, x, y):
xroot = self.find(parent, x)
yroot = self.find(parent, y)

# Attach smaller rank tree under root of


# high rank tree (Union by Rank)
if rank[xroot] < rank[yroot]:
parent[xroot] = yroot
elif rank[xroot] > rank[yroot]:
parent[yroot] = xroot

# If ranks are same, then make one as root


# and increment its rank by one
else:
parent[yroot] = xroot
rank[xroot] += 1

# The main function to construct MST using Kruskal's


# algorithm
def KruskalMST(self):

result = [] # This will store the resultant MST

# An index variable, used for sorted edges


i=0

# An index variable, used for result[]


e=0

# Step 1: Sort all the edges in


# non-decreasing order of their
388 Data Structures Design Laboratory

# weight. If we are not allowed to change the


# given graph, we can create a copy of graph
self.graph = sorted(self.graph,
key=lambda item: item[2])

parent = []
rank = []

# Create V subsets with single elements


for node in range(self.V):
parent.append(node)
rank.append(0)

# Number of edges to be taken is equal to V-1


while e < self.V - 1:

# Step 2: Pick the smallest edge and increment


# the index for next iteration
u, v, w = self.graph[i]
i=i+1
x = self.find(parent, u)
y = self.find(parent, v)

# If including this edge doesn't


# cause cycle, include it in result
# and increment the indexof result
# for next edge
if x != y:
e=e+1
result.append([u, v, w])
self.union(parent, rank, x, y)
# Else discard the edge

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:

Edges in the constructed MST


2 -- 3 == 4
0 -- 3 == 5
0 -- 1 == 10
Minimum Spanning Tree 19

You might also like