SYCS Data Structure Practical Manual(Www.profajaypashankar.com)
SYCS Data Structure Practical Manual(Www.profajaypashankar.com)
STRUCTURES
PRACTICAL MANUAL:
BY PROF.AJAY
PASHANKAR
SYBSC CS SEM III DATA STRUCTURES PRACTICAL MANUAL BY: PROF.AJAY PASHANKAR
return stack.pop()
Output-
Page 1 of 33
www.profajaypashankar.com
SYBSC CS SEM III DATA STRUCTURES PRACTICAL MANUAL BY: PROF.AJAY PASHANKAR
Point to Remember:
------
Note: you can’t remove any element from empty stack you will receive stack underflow
Exception.
You can’t add any element if stack is already full if you do so , you will receive stack
overflow Exception.
-------------------------------------------------------------------------------------------------------------
Program 1A1) STACK ADT USING LIST
# Python program to demonstrate stack implementation using list
stack = []
print('Initial stack')
print(stack)
# uncommenting print(stack.pop())
# will cause an IndexError
# as the stack is now empty
OUTPUT:
Page 2 of 33
www.profajaypashankar.com
SYBSC CS SEM III DATA STRUCTURES PRACTICAL MANUAL BY: PROF.AJAY PASHANKAR
You can implement stack with deque , queue and singly linked List .
Program 1A.2)
# Python program to demonstrate stack implementation using collections.deque
print('Initial stack:')
print(stack)
# uncommenting print(stack.pop())
# will cause an IndexError
# as the stack is now empty
OUTPUT:
Page 3 of 33
www.profajaypashankar.com
SYBSC CS SEM III DATA STRUCTURES PRACTICAL MANUAL BY: PROF.AJAY PASHANKAR
-------------------------------------------------------------------------------------------------------------
PROGRAM 1.A.3 STACK Implementation using queue
#Python program to demonstrate stack implementation using queue module
# Initializing a stack
stack = LifoQueue(maxsize=3)
Page 4 of 33
www.profajaypashankar.com
SYBSC CS SEM III DATA STRUCTURES PRACTICAL MANUAL BY: PROF.AJAY PASHANKAR
Functions available in queue module
maxsize – Number of items allowed in the queue.
empty() – Return True if the queue is empty, False otherwise.
full() – Return True if there are maxsize items in the queue. If the queue was initialized with
maxsize=0 (the default), then full() never returns True.
get() – Remove and return an item from the queue. If the queue is empty, wait until an item is
available.
get_nowait() – Return an item if one is immediately available, else raise QueueEmpty.
put(item) – Put an item into the queue. If the queue is full, wait until a free slot is available
before adding the item.
put_nowait(item) – Put an item into the queue without blocking. If no free slot is immediately
available, raise QueueFull.
qsize() – Return the number of items in the queue.
-------------------------------------------------------------------------------------------------------------------
PROGRAM 1A4)
Implementation STACK ADT using a singly linked list
# Python program to demonstrate stack implementation using a linked list.
# node class
class Node:
def __init__(self, value):
self.value = value
self.next = None
class Stack:
# Initializing a stack.
# Use a dummy node, which is
# easier for handling edge cases.
def __init__(self):
self.head = Node("head")
self.size = 0
# String representation of the stack
def __str__(self):
cur = self.head.next
out = ""
while cur:
out += str(cur.value) + "->"
cur = cur.next
return out[:-3]
# Get the current size of the stack
def getSize(self):
return self.size
# Driver Code
if __name__ == "__main__":
stack = Stack()
for i in range(1, 11):
stack.push(i)
print(f"Stack: {stack}")
OUTPUT:
Methods :
The linked list has two methods addHead(item) and removeHead() that run in constant time.
These two methods are suitable to implement a stack.
getSize()– Get the number of items in the stack.
isEmpty() – Return True if the stack is empty, False otherwise.
peek() – Return the top item in the stack. If the stack is empty, raise an exception.
push(value) – Push a value into the head of the stack.
pop() – Remove and return a value in the head of the stack. If the stack is empty, raise an
exception.
-------------------------------------------------------------------------------------------------------------------
Page 6 of 33
www.profajaypashankar.com
SYBSC CS SEM III DATA STRUCTURES PRACTICAL MANUAL BY: PROF.AJAY PASHANKAR
Program 1B QUEUE ADT
# Python program to demonstrate queue implementation using list
# Initializing a queue
queue = []
print("Initial queue")
print(queue)
OUTPUT:
METHODS USED:
Enqueue: Adds an item to the queue. If the queue is full, then it is said to be an Overflow
condition – Time Complexity : O(1)
Dequeue: Removes an item from the queue. The items are popped in the same order in which
they are pushed. If the queue is empty, then it is said to be an Underflow condition – Time
Complexity : O(1)
Front: Get the front item from queue – Time Complexity : O(1)
Rear: Get the last item from queue – Time Complexity : O(1)
-------------------------------------------------------------------------------------------------------------
Page 7 of 33
www.profajaypashankar.com
SYBSC CS SEM III DATA STRUCTURES PRACTICAL MANUAL BY: PROF.AJAY PASHANKAR
PROGRAM 1C: implementation of LIST ADT.
# Declaring a list with integer and string elements
list = [10, 20, 30, "New Delhi", "Mumbai"]
# printing list
print("List elements are: ", list)
# adding elements
list.append (40)
list.append (50)
list.append ("Chennai")
# removing elements
list.pop () ;
# printing list
print ("List elements: ", list)
# removing elements
list.pop () ;
# printing list
print ("List elements: ", list)
OUTPUT:
Methods used:
Python List append() Method
It is used to add/append an object (which will be passed in method as parameter) to the list.
Syntax:
list.append(element)
Here,
list - is the name of the list.
append() - is the method name, that is used to add element/object to the list.
element - is an element (which is considered as on object or element) to be added in the list.
Python List pop() Method
It is used to remove/pop an object from the list.
Syntax:
list.pop()
Here,
list is the name of the list.
pop() is the method name that is used to remove last element from the list.
-------------------------------------------------------------------------------------------------------------------
Page 8 of 33
www.profajaypashankar.com
SYBSC CS SEM III DATA STRUCTURES PRACTICAL MANUAL BY: PROF.AJAY PASHANKAR
Practical 2-Write a program to implement Singly Linked list with insertion, deletion, traversal
operations .
Practical 2(A)-Write a program to implement singly linked list with insertion
# A complete working Python program to demonstrate all insertion methods of linked list
# Node class
class Node:
# Insert 8, after 7. So linked list becomes 1 -> 7-> 8-> 6-> 4-> None
llist.insertAfter(llist.head.next, 8)
Output-
Page 10 of 33
www.profajaypashankar.com
SYBSC CS SEM III DATA STRUCTURES PRACTICAL MANUAL BY: PROF.AJAY PASHANKAR
Practical 2(B)- write a program to implement singly linked list with deletion
# A complete working Python3 program to
# demonstrate deletion in singly
# linked list with class
# Node class
class Node:
class LinkedList:
temp = None
# Driver program
llist = LinkedList()
llist.push(7)
llist.push(1)
llist.push(3)
llist.push(2)
Output-
# Node class
class Node:
class LinkedList:
def __init__(self):
self.head = None
# Driver code
list1 = LinkedList()
list1.push(5)
list1.push(4)
list1.push(2)
list1.push(3)
list1.push(1)
list1.printMiddle()
Output-
Methods used:
insert(): Add an item to the linked list at the head of the list
find(): Find an item within the linked list
remove(): Remove a given item with a given value
is_empty(): Returns whether the linked list is empty or not
get_count(): Returns the number of items in the linked list
deleteAt(index): delete an item at a given index
findAt(index): find the item at the given index
insertAt(index): insert an item at a given index
-------------------------------------------------------------------------------------------------------------------
Page 13 of 33
www.profajaypashankar.com
SYBSC CS SEM III DATA STRUCTURES PRACTICAL MANUAL BY: PROF.AJAY PASHANKAR
Practical 3-Write a program to implement Doubly Linked list with insertion, deletion, traversal
operations
Practical 3(A)- Write a program to implement doubly linked list with insertion.
# Create the Node class
class Node:
def __init__(self, data):
self.data = data
self.next = None
self.prev = None
dllist = doubly_linked_list()
dllist.push(12)
dllist.push(8)
dllist.push(62)
dllist.insert(dllist.head.next, 13)
dllist.listprint(dllist.head)
Output-
Page 14 of 33
www.profajaypashankar.com
SYBSC CS SEM III DATA STRUCTURES PRACTICAL MANUAL BY: PROF.AJAY PASHANKAR
Practical 3(B)-Write a program to implement doubly linked list with deletion
# Program to delete a node in a doubly-linked list For Garbage collection
import gc
class DoublyLinkedList:
# Base Case
if self.head is None or dele is None:
return
# 1. Allocates node
# 2. Put the data in it
new_node = Node(new_data)
Page 15 of 33
www.profajaypashankar.com
SYBSC CS SEM III DATA STRUCTURES PRACTICAL MANUAL BY: PROF.AJAY PASHANKAR
# Driver code
# Start with empty list
dll = DoublyLinkedList()
Output-
-------------------------------------------------------------------------------------------------------------------
Practical 3( C )- Traversal operation in doubly linked list
class Node:
def __init__(self, data):
self.item = data
self.nref = None
self.pref = None
class DoublyLinkedList:
def __init__(self):
Page 16 of 33
www.profajaypashankar.com
SYBSC CS SEM III DATA STRUCTURES PRACTICAL MANUAL BY: PROF.AJAY PASHANKAR
self.start_node = None
def traverse_list(self):
if self.start_node is None:
print("List has no element")
return
else:
n = self.start_node
while n is not None:
print(n.item , " ")
n = n.nref
OUTPUT:
Page 18 of 33
www.profajaypashankar.com
SYBSC CS SEM III DATA STRUCTURES PRACTICAL MANUAL BY: PROF.AJAY PASHANKAR
Practical 4-Write a program to implement Stack with insertion, deletion, traversal operations
# Python program to
# demonstrate stack implementation
# using collections.deque
stack = deque()
print('Initial stack:')
print(stack)
# uncommenting print(stack.pop())
# will cause an IndexError
# as the stack is now empty
Output-
Page 19 of 33
www.profajaypashankar.com
SYBSC CS SEM III DATA STRUCTURES PRACTICAL MANUAL BY: PROF.AJAY PASHANKAR
Practical 5-Write a program to implement Queue with insertion, deletion, traversal
operations.
# Python program to
# demonstrate queue implementation
# using list
# Initializing a queue
queue = []
print("Initial queue")
print(queue)
# Uncommenting print(queue.pop(0))
# will raise and IndexError
# as the queue is now empty
Output-
Page 20 of 33
www.profajaypashankar.com
SYBSC CS SEM III DATA STRUCTURES PRACTICAL MANUAL BY: PROF.AJAY PASHANKAR
Practical 6-Write a program to implement Priority Queue with insertion, deletion, traversal
operations
self.data = value
self.priority = pr
self.next = None
def __init__(self):
self.front = None
else:
# Assigning it to self.front
self.front = newNode
Page 21 of 33
www.profajaypashankar.com
SYBSC CS SEM III DATA STRUCTURES PRACTICAL MANUAL BY: PROF.AJAY PASHANKAR
else:
while temp.next:
temp = temp.next
newNode = PriorityQueueNode(value,priority)
newNode.next = temp.next
temp.next = newNode
else:
Page 22 of 33
www.profajaypashankar.com
SYBSC CS SEM III DATA STRUCTURES PRACTICAL MANUAL BY: PROF.AJAY PASHANKAR
print(temp.data, end = " ")
temp = temp.next
# Driver code
if __name__ == "__main__":
Output-
Page 23 of 33
www.profajaypashankar.com
SYBSC CS SEM III DATA STRUCTURES PRACTICAL MANUAL BY: PROF.AJAY PASHANKAR
Practical 7- Write a program to implement Binary Tree with insertion, deletion, traversal
operations
Practical 7(A)- BST with insertion
class Tree:
Output-
else:
if (node.left is None and node.right is None):
if(temp.left == node):
temp.left = None
else:
temp.right = None
node = None
else:
temp = node.right
while(temp.left is not None):
temp = temp.left
node.value = temp.value
node.right.Delete(temp,temp.value)
Root = Tree(6)
Root.Insert(4)
Root.Insert(2)
Root.Insert(5)
Root.Insert(9)
Root.Insert(8)
Root.Insert( 10)
Page 25 of 33
www.profajaypashankar.com
SYBSC CS SEM III DATA STRUCTURES PRACTICAL MANUAL BY: PROF.AJAY PASHANKAR
Root.Delete(Root, 4)
print ('\n 4 is deleted: ',end ='')
Root.Inorder(Root)
Root.Delete(Root, 6)
print ('\n 6 is deleted: ',end ='')
Root.Inorder(Root)
Output-
class Node:
def __init__(self, key):
self.left = None
self.right = None
self.val = key
if root:
if root:
Page 26 of 33
www.profajaypashankar.com
SYBSC CS SEM III DATA STRUCTURES PRACTICAL MANUAL BY: PROF.AJAY PASHANKAR
if root:
# Driver code
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
print ("Preorder traversal of binary tree is")
printPreorder(root)
Page 27 of 33
www.profajaypashankar.com
SYBSC CS SEM III DATA STRUCTURES PRACTICAL MANUAL BY: PROF.AJAY PASHANKAR
Practical 8-Write a Program to implement Huffman Coding.
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 __str__(self):
return self.left, self.right
def make_tree(nodes):
'''
Function to make tree
:param nodes: Nodes
:return: Root of the tree
'''
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)
return nodes[0][0]
if __name__ == '__main__':
string = 'BCAADDDCCACACAC'
freq = dict(Counter(string))
freq = sorted(freq.items(), key=lambda x: x[1], reverse=True)
node = make_tree(freq)
encoding = huffman_code_tree(node)
for i in encoding:
print(f'{i} : {encoding[i]}')
Page 28 of 33
www.profajaypashankar.com
SYBSC CS SEM III DATA STRUCTURES PRACTICAL MANUAL BY: PROF.AJAY PASHANKAR
Output-
-------------------------------------------------------------------------------------------------------------
Practical 9-Write a program to implement Graph with insertion, deletion, traversal operations.
import collections
# BFS algorithm
def bfs(graph, root):
while queue:
if __name__ == '__main__':
graph = {0: [1, 2], 1: [2], 2: [3], 3: [1, 2]}
print("Following is Breadth First Traversal: ")
Page 29 of 33
www.profajaypashankar.com
SYBSC CS SEM III DATA STRUCTURES PRACTICAL MANUAL BY: PROF.AJAY PASHANKAR
bfs(graph, 0)
Output-
-------------------------------------------------------------------------------------------------------------
Practical 10-
Write a program to implement Travelling Salesman Problem.
------------------------------------------------------------------------------------------------------------
Travelling Salesman Problem
Travelling Sales Person Problem
The traveling salesman problems abide by a salesman and a set of cities. The salesman has to visit
every one of the cities starting from a certain one (e.g., the hometown) and to return to the same city.
The challenge of the problem is that the traveling salesman needs to minimize the total length of the
trip.
Suppose the cities are x1 x2..... xn where cost cij denotes the cost of travelling from city xi to xj. The
travelling salesperson problem is to find a route starting and ending at x1 that will take in all cities with
the minimum cost.
Example: A newspaper agent daily drops the newspaper to the area assigned in such a manner that
he has to cover all the houses in the respective area with minimum travel cost. Compute the minimum
travel cost.
-------------------------------------------------------------------------------------------------------------------
# Python3 program to implement traveling salesman
# problem using naive approach.
# update minimum
min_path = min(min_path, current_pathweight)
Page 30 of 33
www.profajaypashankar.com
SYBSC CS SEM III DATA STRUCTURES PRACTICAL MANUAL BY: PROF.AJAY PASHANKAR
return min_path
# Driver Code
if __name__ == "__main__":
Output-
-------------------------------------------------------------------------------------------------------------
Practical 11-Write a program to create basic Hash Table for insertion, deletion, traversal
operations(assume that there are no collisions)
# Python program to demonstrate working of HashTable
hashTable = [[],] * 10
# Python program to demonstrate working of HashTable
hashTable = [[],] * 10
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")
Page 31 of 33
www.profajaypashankar.com
SYBSC CS SEM III DATA STRUCTURES PRACTICAL MANUAL BY: PROF.AJAY PASHANKAR
insertData(432, "mango")
insertData(213, "banana")
insertData(654, "guava")
print(hashTable)
removeData(123)
print(hashTable)
Output-
Page 32 of 33
www.profajaypashankar.com
SYBSC CS SEM III DATA STRUCTURES PRACTICAL MANUAL BY: PROF.AJAY PASHANKAR
Practical 12-Write a program to create hash table to handle collisions using overflow chaining.
for i in range(len(hashTable)):
print(i, end = " ")
for j in hashTable[i]:
print("-->", end = " ")
print(j, end = " ")
print()
# Creating Hashtable as
# a nested list.
HashTable = [[] for _ in range(10)]
hash_key = Hashing(keyvalue)
Hashtable[hash_key].append(value)
# Driver Code
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-
Page 33 of 33
www.profajaypashankar.com