0% found this document useful (0 votes)
27 views14 pages

DS Practical

The document contains multiple practical programming exercises implementing various data structures and algorithms in Python. It covers the implementation of Stack, Singly Linked List, Doubly Linked List, Queue, Priority Queue, Binary Tree, Huffman Coding, and Graph with operations such as insertion, deletion, and traversal. Each section includes code snippets and sample outputs demonstrating the functionality of the implemented data structures.

Uploaded by

immanuelrocks63
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views14 pages

DS Practical

The document contains multiple practical programming exercises implementing various data structures and algorithms in Python. It covers the implementation of Stack, Singly Linked List, Doubly Linked List, Queue, Priority Queue, Binary Tree, Huffman Coding, and Graph with operations such as insertion, deletion, and traversal. Each section includes code snippets and sample outputs demonstrating the functionality of the implemented data structures.

Uploaded by

immanuelrocks63
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 14

PRACTICAL NO – 01

Write a program to implement abstract data types (ADT)


class Stack:
def init (self):
self.items=[]
def is_empty(self):
return len(self.items) ==0
def push(self,items):
self.items.append(items)
def pop(self):
if self.is_empty():
raise IndexError("pop from empty stack")
return self.items.pop()
def peek(self):
if self.is_empty():
raise IndexError("peek from empty stack")
return self.items[-1]
def size(self):
return len(self.items)
if name ==" main ":
stack=Stack()
stack.push(1)
stack.push(2)
stack.push(3)
stack.push(4)
print("Top of stack is",stack.peek())
print("Stack Size is",stack.size())
print("Pop from stack",stack.pop())

OUTPUT:
PRACTICAL NO – 02
Write a program to implement singly linked list with insertion, deletion, transversal
operations

# Node class representing each element of the linked list


class Node:
def __init__(self, data):
self.data = data # Holds the value of the node
self.next = None # Points to the next node in the list

# Singly Linked List class


class SinglyLinkedList:
def __init__(self):
self.head = None # The head of the linked list (initially None)

# Insertion at the end of the list


def insert(self, data):
new_node = Node(data) # Create a new node
if self.head is None: # If the list is empty, new node is the head
self.head = new_node
else:
current = self.head
# Traverse to the end of the list
while current.next:
current = current.next
# Link the new node to the end of the list
current.next = new_node

# Deletion of a node with a specific value


def delete(self, data):
current = self.head
# If the list is empty
if current is None:
print("List is empty.")
return

# If the node to be deleted is the head


if current.data == data:
self.head = current.next # Move head to the next node
current = None
return

# Otherwise, traverse the list to find the node to delete


prev = None
while current and current.data != data:
PRACTICAL NO – 02
prev = current
current = current.next

# If the node was not found


if current is None:
print("Node with data", data, "not found.")
return

# Unlink the node to delete it


prev.next = current.next
current = None

# Traversal (printing the entire linked list)


def traverse(self):
current = self.head
if current is None:
print("List is empty.")
return

while current:
print(current.data, end=" -> ")
current = current.next
print("None")

# Main block to test the implementation


if __name__ == "__main__":
sll = SinglyLinkedList()

# Inserting elements into the list


sll.insert(10)
sll.insert(20)
sll.insert(30)
sll.insert(40)

# Traversing the list


print("Linked List after insertion:")
sll.traverse()

# Deleting an element from the list


sll.delete(20)

# Traversing the list after deletion


print("Linked List after deleting 20:")
sll.traverse()
PRACTICAL NO – 02
# Deleting an element that is not in the list
sll.delete(50)

# Traversing the list again


print("Linked List after attempting to delete 50:")
sll.traverse()

Output:
Linked List after insertion:
10 -> 20 -> 30 -> 40 -> None
Linked List after deleting 20:
10 -> 30 -> 40 -> None
Node with data 50 not found.
Linked List after attempting to delete 50:
10 -> 30 -> 40 -> None
PRACTICAL NO – 03
Write a program to implement Doubly Linked List with insertion, Deletion, Traversal
operations
import gc
class Node:
def init (self,data):
self.item=data
self.next=None
self.prev=None
class doublyLinkedlist:
def init (self):
self.start_node=None
def InsertToEmptylist(self,data):
if self.start_node is None:
new_node=Node(data)
self.start_node=new_node
else:
print("the list is empty")
def InsertToEnd(self,data):
if self.start_node is None:
new_node=Node(data)
self.start_node=new_node
return
n=self.start_node
while n.next is not None:
n=n.next
new_node=Node(data)
n.next =new_node
new_node.prev=n
def DeleteAtStart(self):
if self.start_node is None:
print(" The Linked List is empty")
return
if self.start_node is None:
self.start_node=None
return
self.start_node=self.start_node.next
self.start_prev=None;
def delete_at_end(self):
if self.start_node is None:
print("the list is empty")
return
if self.start_node.next is None:
self.start_node=None
return
n=self.start_node
while n.next is not None:
n=n.next
n.prev.next=None
def Display(self):
if self.start_node is None:
print("the list is empty")
return
else:
n=self.start_node
while n is not None:
print("Element is:",n.item)
n=n.next
print("\n")
NewDoublyLinkedList =doublyLinkedlist()
NewDoublyLinkedList.InsertToEmptylist(10)
NewDoublyLinkedList.InsertToEnd(20)
NewDoublyLinkedList.InsertToEnd(30)
NewDoublyLinkedList.InsertToEnd(40)
NewDoublyLinkedList.InsertToEnd(50)
NewDoublyLinkedList.InsertToEnd(60)
NewDoublyLinkedList.Display()
NewDoublyLinkedList.DeleteAtStart()
NewDoublyLinkedList.delete_at_end()
NewDoublyLinkedList.Display()

OUTPUT:
PRACTICAL NO – 04
Write a program to implement stack with insertion, deletion and transversal operations
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:
PRACTICAL NO – 05
Write a program to implement Queue with insertion, deletion, transversal operations
class Queue:
def init (self):
self.queue=[]
def is_empty(self):
return len(self.queue)==0
def enqueue(self,item):
self.queue.append(item)
print(f"Enqueued:{item}")
def dequeue(self):
if self.is_empty():
print("queue is empty cannot deque")
return None
return self.queue.pop(0)
def traverse(self):
if self.is_empty():
print("queue is empty")
else:
print("Queue Elements")
for item in self.queue:
print(item,end=" ")
print()
if name ==" main ":
q=Queue()
q.enqueue(10)
q.enqueue(20)
q.enqueue(30)
q.traverse()
print(f"Dequeued:{q.dequeue()}")
print(f"Dequeued:{q.dequeue()}")
q.dequeue()
q.traverse()

OUTPUT:
PRACTICAL NO – 06
Write a program to implement Priority Queue with insertion, deletion, transversal
operations
class PriorityQueue:
def init (self):
self.queue=[]
def is_empty(self):
return len(self.queue)==0
def enqueue(self,item,priority):
self.queue.append((item,priority))
self.queue.sort(key=lambda x:x[1],reverse=True)
print("Enqueued:{item} with priority{priority}")
def dequeue(self):
if self.is_empty():
print("priority queue is empty. Cannot Dequeue")
return None
return self.queue.pop(0)[0]
def traverse(self):
if self.is_empty():
print('priority queue is empty')
return
print('priority queue elements:')
for item,priority in self.queue:
print(f"item:{item},priority:{priority}",end='')
print()
if name ==" main ":
pq = PriorityQueue()
pq.enqueue('task1',3)
pq.enqueue('task2',1)
pq.enqueue('task3',2)
pq.traverse()
print(f"Dequeued:{pq.dequeue()}")
pq.traverse() print(f"Dequeued:
{pq.dequeue()}")
print(f"Dequeued:{pq.dequeue()}")
pq.dequeue()
pq.traverse()
OUTPUT:
PRACTICAL NO – 07
Write a program to implement Binary Tree with Insertion, Deletion, Traversal
operations
class Node:
def init (self,key):
self.left = None
self.right = None
self.val = key
def traversePreOrder(self):
print(self.val,end='')
if self.left:
self.left.traversePreOrder()
if self.right:
self.right.traversePreOrder()
def traverseInOrder(self):
if self.left:
self.left.traverseInOrder()
print(self.val,end=' ')
if self.right:
self.right.traverseInOrder()
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)
print("Pre order Traversal:",end="")
root.traversePreOrder()
print("\nIn order Traversal:",end="")
root.traverseInOrder()
print("\nPost order Traversal:",end="")
root.traversePostOrder()

OUTPUT:
PRACTICAL NO – 08
Write a program to implement Huffman Coding
string='BCAADDDCCACACAC'
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)
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
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:
Practical 9
Write a program to implement Graph with insertion, deletion,
traversal operations

from collections import defaultdict

graph = defaultdict(list)
def addEdge(graph,u,v):
graph[u].append(v)

def generate_edges(graph):
edges=[]

for node in graph:

for neighbour in graph[node]:

edges.append((node,neighbour))

return edges
addEdge(graph,'a','c')
addEdge(graph,'b','c')
addEdge(graph,'b','e')
addEdge(graph,'c','d')
addEdge(graph,'c','e')
addEdge(graph,'c','a')
addEdge(graph,'c','b')
addEdge(graph,'e','b')
addEdge(graph,'d','c')
addEdge(graph,'e','c')

print(generate_edges(graph))

Output:
[('a', 'c'), ('b', 'c'), ('b', 'e'), ('c', 'd'), ('c', 'e'), ('c', 'a'), ('c', 'b'), ('e', 'b'), ('e', 'c'), ('d', 'c')]

You might also like