0% found this document useful (0 votes)
8 views21 pages

Data Structures With Python Lab Manual

Uploaded by

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

Data Structures With Python Lab Manual

Uploaded by

shwethapujar85
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Government Polytechnic Joida (162) Dept of CSE

Government of Karnataka
Department of Technical Education

Data Structures with


Python
LAB RECORD / MANUAL
Sayyan Shaikh
Course Code: 25CS33I
Program: Computer Science and Engineering
Academic Year: 2025- 2026

Student Name: USN: Semester

162CS III

Data Structures with Python (25CS33I) — Lab Manual Page 1


Government Polytechnic Joida (162) Dept of CSE

How to Use This Lab Manual


Every week in this manual is laid out the same way, so you always know where to look.

Section What it gives you


Problem Statement The real-world task you must solve (blue box).
Data Structure Used Which structure fits the problem, and why (teal box).
Algorithm The solution written as numbered, plain-English steps.
Python Program Simple, working code you can type directly.
Sample Output The exact output produced when the program is run.
Trick to Remember A short memory hook so you can rewrite the code in the exam (amber
box).
How to practise: read the problem, decide the data structure yourself, then try the algorithm
before reading the code. Type the program, run it, and check your output against the Sample
Output.

Data Structures with Python (25CS33I) — Lab Manual Page 2


Government Polytechnic Joida (162) Dept of CSE

LAB — WEEK 1
Working with a List of Marks

Problem
PROBLEM STATEMENT
Store the marks of five students. Display them, add a new mark, delete a wrong mark,
search for a mark, and find the highest, lowest and average.

Data Structure Used


DATA STRUCTURE USED
List
A list is ordered and changeable, so it is perfect for a group of marks that we need to add to,
delete from and search.

Algorithm
Step 1. Create a list with the five marks.
Step 2. Print the list (traversal).
Step 3. Use append() to add a new mark at the end.
Step 4. Use remove() to delete the wrong mark.
Step 5. Use index() to find the position of a mark.
Step 6. Use max() and min() for highest and lowest.
Step 7. Add all marks in a loop and divide by len() for the average.
Step 8. Print every result.

Python Program
week1_marks.py
marks = [55, 82, 47, 90, 68]
print("Original:", marks)

[Link](75) # insertion
print("After insert 75:", marks)

[Link](47) # deletion
print("After delete 47:", marks)

print("Search 90 at index:", [Link](90))


print("Highest:", max(marks), " Lowest:", min(marks))

total = 0
for m in marks: # traversal
total += m
print("Average:", total/len(marks))

SAMPLE OUTPUT
Original: [55, 82, 47, 90, 68]
After insert 75: [55, 82, 47, 90, 68, 75]
After delete 47: [55, 82, 90, 68, 75]
Search 90 at index: 2
Highest: 90 Lowest: 55
Average: 74.0

TRICK TO REMEMBER THE CODE


A-R-I-M-M = Append, Remove, Index, Max, Min. The five list jobs in order.
Remember: append adds, remove deletes by value, index finds the spot.

Data Structures with Python (25CS33I) — Lab Manual Page 3


Government Polytechnic Joida (162) Dept of CSE

LAB — WEEK 2
Student Enrollment with Sets

Problem
PROBLEM STATEMENT
Two subjects, Python and Java, have enrolled students. Find who is enrolled in both,
who is only in Python, and the full list of students. Also store one student's fixed record.

Data Structure Used


DATA STRUCTURE USED
Set (and a Tuple)
A set stores unique names and supports common-student operations directly (intersection,
difference, union). A tuple holds the fixed student record that should not change.

Algorithm
Step 1. Create two sets: python_students and java_students.
Step 2. Use & (intersection) for students in both.
Step 3. Use - (difference) for students only in Python.
Step 4. Use | (union) for all students.
Step 5. Create a tuple for one student's fixed record (id, name, dept).
Step 6. Print every result.

Python Program
week2_enrollment.py
python_students = {"Asha", "Ravi", "Kiran", "Meena"}
java_students = {"Ravi", "Meena", "Sara"}

print("Enrolled in both :", python_students & java_students)


print("Only in Python :", python_students - java_students)
print("All students :", python_students | java_students)

student = ("S101", "Asha", "CSE") # fixed record (tuple)


print("Record -> ID:", student[0], "Name:", student[1], "Dept:", student[2])

SAMPLE OUTPUT
Enrolled in both : {'Meena', 'Ravi'}
Only in Python : {'Asha', 'Kiran'}
All students : {'Sara', 'Ravi', 'Kiran', 'Asha', 'Meena'}
Record -> ID: S101 Name: Asha Dept: CSE
Note: a set has no order, so the names may print in any order — that is normal and still
correct.

TRICK TO REMEMBER THE CODE


& = And (in both). - = remove the other group. | = all together.
Sets use curly braces { }; a tuple uses round brackets ( ) and cannot change.

Data Structures with Python (25CS33I) — Lab Manual Page 4


Government Polytechnic Joida (162) Dept of CSE

LAB — WEEK 3
Employee Payroll with Dictionaries

Problem
PROBLEM STATEMENT
Store each employee's name and salary. Find the total salary paid by the company and
the highest-paid employee.

Data Structure Used


DATA STRUCTURE USED
List of Dictionaries
Each employee is a dictionary of name : value pairs, and the list holds many employees. This
models a real record table cleanly.

Algorithm
Step 1. Create a list where each item is a dictionary with name and salary.
Step 2. Set total to 0 and loop through the list, adding each salary.
Step 3. Set highest to the first employee.
Step 4. Loop again; if an employee's salary is greater, make them the new highest.
Step 5. Print the total and the highest-paid employee.

Python Program
week3_payroll.py
employees = [
{"name": "Ravi", "salary": 40000},
{"name": "Asha", "salary": 55000},
{"name": "Kiran", "salary": 48000},
]

total = 0
for e in employees:
total += e["salary"]
print("Total salary :", total)

highest = employees[0]
for e in employees:
if e["salary"] > highest["salary"]:
highest = e
print("Highest paid :", highest["name"], "(", highest["salary"], ")")

SAMPLE OUTPUT
Total salary : 143000
Highest paid : Asha ( 55000 )

TRICK TO REMEMBER THE CODE


Pattern for “find the biggest”: assume first is best, then loop and replace.
Read each record with e["key"] — the key is the column name.

Data Structures with Python (25CS33I) — Lab Manual Page 5


Government Polytechnic Joida (162) Dept of CSE

LAB — WEEK 4
Word Frequency Report (Strings + File)

Problem
PROBLEM STATEMENT
Take a sentence, count how many times each word appears, and save the report to a
file. Then read the file back and show it.

Data Structure Used


DATA STRUCTURE USED
Dictionary (with String and File operations)
A dictionary maps each word to its count. The string method split() breaks the sentence into
words, and a file stores the report permanently.

Algorithm
Step 1. Split the sentence into a list of words using split().
Step 2. Create an empty dictionary freq.
Step 3. For each word, increase its count using get(word, 0) + 1.
Step 4. Open a file in write mode and write each word with its count.
Step 5. Open the same file in read mode and print its contents.

Python Program
week4_word_report.py
text = "data is the new oil data drives ai and data is power"
words = [Link]()

freq = {}
for w in words:
freq[w] = [Link](w, 0) + 1

with open("[Link]", "w") as f:


[Link]("Word Frequency Report\n")
for w, c in [Link]():
[Link](f"{w}: {c}\n")

with open("[Link]", "r") as f:


print([Link]())

SAMPLE OUTPUT
Word Frequency Report
data: 3
is: 2
the: 1
new: 1
oil: 1
drives: 1
ai: 1
and: 1
power: 1

TRICK TO REMEMBER THE CODE


Counting trick: freq[w] = [Link](w, 0) + 1 — “get the old count or 0, add one”.
File trick: with open(...) auto-closes; "w" writes, "r" reads.

Data Structures with Python (25CS33I) — Lab Manual Page 6


Government Polytechnic Joida (162) Dept of CSE

LAB — WEEK 5
Safe Payment with Exception Handling
Problem
PROBLEM STATEMENT
Process a payment from a balance. Reject invalid amounts (not a number, zero or
negative) and payments larger than the balance, without crashing the program.

Data Structure Used


DATA STRUCTURE USED
try / except / finally blocks
Exception handling is the right tool here — it lets the program catch bad input and keep
running instead of stopping with an error.

Algorithm
Step 1. Define a function with the balance and the amount.
Step 2. Inside try, convert the amount to a number.
Step 3. If the amount is zero or negative, raise a ValueError.
Step 4. If the amount is more than the balance, raise a ValueError.
Step 5. Otherwise subtract it and print the new balance.
Step 6. In except, print why the payment failed.
Step 7. In finally, print that the attempt is finished.
Step 8. Call the function with a valid amount, a non-number, and a too-large amount.

Python Program
week5_payment.py
def make_payment(balance, amount):
try:
amount = float(amount)
if amount <= 0:
raise ValueError("Amount must be positive")
if amount > balance:
raise ValueError("Insufficient balance")
balance -= amount
print(f"Paid {amount}. New balance: {balance}")
except ValueError as e:
print("Payment failed:", e)
finally:
print("Transaction attempt finished")

make_payment(1000, 300)
make_payment(1000, "abc")
make_payment(1000, 5000)

SAMPLE OUTPUT
Paid 300.0. New balance: 700.0
Transaction attempt finished
Payment failed: could not convert string to float: 'abc'
Transaction attempt finished
Payment failed: Insufficient balance
Transaction attempt finished

TRICK TO REMEMBER THE CODE


Try – Except – Finally = “Try it, catch the problem, always finish.”
Use raise ValueError(...) to reject bad data on purpose; finally always runs.

Data Structures with Python (25CS33I) — Lab Manual Page 7


Government Polytechnic Joida (162) Dept of CSE

LAB — WEEK 6
Total Folder Size using Recursion

Problem
PROBLEM STATEMENT
A folder contains files and sub-folders, and a sub-folder can contain more sub-folders.
Find the total size of everything inside the folder.

Data Structure Used


DATA STRUCTURE USED
Recursion (over a nested list)
A folder inside a folder is the same problem on a smaller scale, which is exactly what
recursion solves. The folder is shown as a nested list of sizes.

Algorithm
Step 1. Define a function total_size that takes a folder (a list).
Step 2. Set total to 0.
Step 3. For each item: if it is a list, it is a sub-folder — call total_size on it (recursive case) and
add the result.
Step 4. Otherwise it is a file size — add the number directly.
Step 5. Return the total.
Step 6. Call the function on a nested list and print the answer.

Python Program
week6_folder_size.py
def total_size(folder):
total = 0
for item in folder:
if isinstance(item, list): # sub-folder
total += total_size(item) # recursive case
else: # a file size
total += item
return total

disk = [10, 20, [5, 5, [2, 3]], 50]


print("Total size:", total_size(disk), "KB")

SAMPLE OUTPUT
Total size: 95 KB

TRICK TO REMEMBER THE CODE


Recursion rule: if it is a box inside a box, call yourself; if it is a plain value, just add it.
Base case here is hidden: when a list has no more sub-lists, the loop simply adds
numbers and stops.

Data Structures with Python (25CS33I) — Lab Manual Page 8


Government Polytechnic Joida (162) Dept of CSE

LAB — WEEK 7
Library Book using a Class (UDT)

Problem
PROBLEM STATEMENT
Model a library book that has a title and a number of copies. Allow a copy to be issued,
and refuse to issue when no copies are left.

Data Structure Used


DATA STRUCTURE USED
User-Defined Type (class)
A class lets us bundle the book's data (title, copies) with its actions (issue, display) into one
neat type — the textbook example of a UDT.

Algorithm
Step 1. Define a class Book.
Step 2. In __init__, store the title and the number of copies.
Step 3. Write an issue() method: if copies remain, reduce by one; else print 'not available'.
Step 4. Write a display() method to show the title and copies.
Step 5. Create a Book object and call display(), then issue() a few times.

Python Program
week7_library.py
class Book:
def __init__(self, title, copies):
[Link] = title
[Link] = copies
def issue(self):
if [Link] > 0:
[Link] -= 1
print(f"Issued '{[Link]}'. Left: {[Link]}")
else:
print(f"'{[Link]}' not available")
def display(self):
print(f"{[Link]} -> {[Link]} copies")

b = Book("Python Basics", 2)
[Link]()
[Link]()
[Link]()
[Link]()

SAMPLE OUTPUT
Python Basics -> 2 copies
Issued 'Python Basics'. Left: 1
Issued 'Python Basics'. Left: 0
'Python Basics' not available

TRICK TO REMEMBER THE CODE


Class skeleton: class → __init__ (self, data) → methods (self).
Every method starts with self; self.x remembers data inside the object.

Data Structures with Python (25CS33I) — Lab Manual Page 9


Government Polytechnic Joida (162) Dept of CSE

LAB — WEEK 8
Browser Back-Button using a Stack

Problem
PROBLEM STATEMENT
Track the pages a user visits. The Back button should always return to the most recently
visited page — last visited, first returned.

Data Structure Used


DATA STRUCTURE USED
Stack (LIFO)
The Back button needs the last page first, which is exactly LIFO behaviour. A Python list used
as a stack fits perfectly.

Push adds a page on top; Back (pop) removes from the top.

Algorithm
Step 1. Start with an empty list called history (the stack).
Step 2. visit(page): append the page (push) and print it.
Step 3. back(): if more than one page exists, pop the top and print the new top page.
Step 4. Otherwise print 'No more history'.
Step 5. Visit three pages, press Back twice, and show the current page.

Python Program
week8_browser_stack.py
history = []

def visit(page):
[Link](page) # push
print("Visited:", page)

def back():
if len(history) > 1:
[Link]() # pop
print("Back to:", history[-1])
else:
print("No more history")

visit("[Link]")
visit("[Link]")

Data Structures with Python (25CS33I) — Lab Manual Page 10


Government Polytechnic Joida (162) Dept of CSE

visit("[Link]")
back()
back()
print("Current page:", history[-1])

SAMPLE OUTPUT
Visited: [Link]
Visited: [Link]
Visited: [Link]
Back to: [Link]
Back to: [Link]
Current page: [Link]

TRICK TO REMEMBER THE CODE


Stack of plates: you add and take from the top only.
push = append(), pop = pop(), top = history[-1].

Data Structures with Python (25CS33I) — Lab Manual Page 11


Government Polytechnic Joida (162) Dept of CSE

LAB — WEEK 9
Support Tickets using a Queue

Problem
PROBLEM STATEMENT
Customer support tickets must be served in the order they arrive — first raised, first
served.

Data Structure Used


DATA STRUCTURE USED
Queue (FIFO) using [Link]
Serving in arrival order is FIFO. A deque removes from the front quickly, which a normal list
does slowly.

Enqueue adds a ticket at the rear; serve (dequeue) removes from the front.

Algorithm
Step 1. Import deque and create an empty queue called tickets.
Step 2. raise_ticket(t): append the ticket at the rear and print it.
Step 3. serve(): if the queue is not empty, popleft the front ticket and print it.
Step 4. Raise three tickets, serve two, and show the tickets still waiting.

Python Program
week9_tickets_queue.py
from collections import deque
tickets = deque()

def raise_ticket(t):
[Link](t) # enqueue
print("Raised:", t)

def serve():
if tickets:
print("Serving:", [Link]()) # dequeue
else:
print("No tickets")

raise_ticket("T1-login issue")
raise_ticket("T2-payment fail")
raise_ticket("T3-password reset")
serve()
serve()
print("Waiting:", list(tickets))

Data Structures with Python (25CS33I) — Lab Manual Page 12


Government Polytechnic Joida (162) Dept of CSE

SAMPLE OUTPUT
Raised: T1-login issue
Raised: T2-payment fail
Raised: T3-password reset
Serving: T1-login issue
Serving: T2-payment fail
Waiting: ['T3-password reset']

TRICK TO REMEMBER THE CODE


Ticket queue: join at the rear, leave from the front.
enqueue = append(), dequeue = popleft(). Always import deque first.

Data Structures with Python (25CS33I) — Lab Manual Page 13


Government Polytechnic Joida (162) Dept of CSE

LAB — WEEK 10
Music Playlist using a Singly Linked List

Problem
PROBLEM STATEMENT
Build a music playlist where each song points to the next song, and you can add songs
and play them in order.

Data Structure Used


DATA STRUCTURE USED
Singly Linked List
Each song is a node holding the song name and a link to the next song. New songs can be
added at the end without shifting anything.

Each node stores a song and a link to the next; the last node points to END (None).

Algorithm
Step 1. Define a Node class with song and next.
Step 2. Define a Playlist class with head set to None.
Step 3. add(song): make a node; if the list is empty set it as head; else walk to the last node
and link it.
Step 4. show(): start at head, print each song, move to next, until None.
Step 5. Add three songs and show the playlist.

Python Program
week10_playlist_sll.py
class Node:
def __init__(self, song):
[Link] = song
[Link] = None

class Playlist:
def __init__(self):
[Link] = None
def add(self, song):
new = Node(song)
if not [Link]:
[Link] = new
return
cur = [Link]
while [Link]:
cur = [Link]
[Link] = new
def show(self):
cur = [Link]

Data Structures with Python (25CS33I) — Lab Manual Page 14


Government Polytechnic Joida (162) Dept of CSE

while cur:
print([Link], end=" -> ")
cur = [Link]
print("END")

p = Playlist()
[Link]("Song A"); [Link]("Song B"); [Link]("Song C")
[Link]()

SAMPLE OUTPUT
Song A -> Song B -> Song C -> END

TRICK TO REMEMBER THE CODE


Treasure-hunt idea: each clue (node) points to the next clue; head is the first clue.
To add at the end: walk with while [Link]: until the last node, then link.

Data Structures with Python (25CS33I) — Lab Manual Page 15


Government Polytechnic Joida (162) Dept of CSE

LAB — WEEK 11
Browser History using a Doubly Linked List

Problem
PROBLEM STATEMENT
Build a browser that can move Back and Forward through visited pages. Each page must
know both the page before it and the page after it.

Data Structure Used


DATA STRUCTURE USED
Doubly Linked List
Back and Forward need links in both directions, so each node stores prev and next — the
defining feature of a doubly linked list.

Each node links to both the previous and the next page.

Algorithm
Step 1. Define a Node class with page, prev and next.
Step 2. Define a Browser class with current set to None.
Step 3. visit(page): make a node; link it to the current page both ways; make it the new
current.
Step 4. back(): if a previous page exists, move current backward; print the current page.
Step 5. forward(): if a next page exists, move current forward; print the current page.
Step 6. Visit three pages, go Back twice, then Forward once.

Python Program
week11_browser_dll.py
class Node:
def __init__(self, page):
[Link] = page
[Link] = None
[Link] = None

class Browser:
def __init__(self):
[Link] = None
def visit(self, page):
node = Node(page)
if [Link]:
[Link] = node
[Link] = [Link]
[Link] = node
print("Visited:", page)
def back(self):

Data Structures with Python (25CS33I) — Lab Manual Page 16


Government Polytechnic Joida (162) Dept of CSE

if [Link]:
[Link] = [Link]
print("Current:", [Link])
def forward(self):
if [Link]:
[Link] = [Link]
print("Current:", [Link])

b = Browser()
[Link]("home"); [Link]("products"); [Link]("cart")
[Link]()
[Link]()
[Link]()

SAMPLE OUTPUT
Visited: home
Visited: products
Visited: cart
Current: products
Current: home
Current: products

TRICK TO REMEMBER THE CODE


Train coaches: each coach is joined to the one ahead and behind.
On visit, set both links: [Link] = node and [Link] = current.

Data Structures with Python (25CS33I) — Lab Manual Page 17


Government Polytechnic Joida (162) Dept of CSE

LAB — WEEK 12
Organisation Hierarchy using a Tree

Problem
PROBLEM STATEMENT
Represent a company hierarchy (CEO at the top, managers below, staff under
managers) and count the total number of people.

Data Structure Used


DATA STRUCTURE USED
Binary Tree
A hierarchy branches from one top person, which is naturally a tree. Each node holds a
person and links to up to two people below.

The CEO is the root; managers and staff are child nodes; staff are the leaves.

Algorithm
Step 1. Define a Node class with data, left and right.
Step 2. Define count_nodes(node): if the node is None, return 0.
Step 3. Otherwise return 1 + count of the left subtree + count of the right subtree (recursion).
Step 4. Build the tree: CEO at the root, two managers, two staff.
Step 5. Call count_nodes on the root and print the total.

Python Program
week12_org_tree.py
class Node:
def __init__(self, data):
[Link] = data
[Link] = None
[Link] = None

def count_nodes(node):
if node is None:
return 0
return 1 + count_nodes([Link]) + count_nodes([Link])

Data Structures with Python (25CS33I) — Lab Manual Page 18


Government Polytechnic Joida (162) Dept of CSE

root = Node("CEO")
[Link] = Node("Manager A")
[Link] = Node("Manager B")
[Link] = Node("Staff 1")
[Link] = Node("Staff 2")
print("Total people in org:", count_nodes(root))

SAMPLE OUTPUT
Total people in org: 5

TRICK TO REMEMBER THE CODE


Counting a tree: 1 (yourself) + left count + right count. A pure recursion pattern.
Empty node = 0 is the base case that stops the recursion.

Data Structures with Python (25CS33I) — Lab Manual Page 19


Government Polytechnic Joida (162) Dept of CSE

LAB — WEEK 13
Tree Traversals (In / Pre / Post / Level)

Problem
PROBLEM STATEMENT
Visit and print every node of a binary tree in the four standard orders: inorder, preorder,
postorder and level-order.

Data Structure Used


DATA STRUCTURE USED
Binary Tree (with recursion and a queue)
The three depth-first orders use recursion; level-order uses a queue to visit the tree row by
row.

The same tree visited in inorder, preorder and postorder.

Algorithm
Step 1. Define a Node class with data, left and right.
Step 2. inorder: visit left, print node, visit right.
Step 3. preorder: print node, visit left, visit right.
Step 4. postorder: visit left, visit right, print node.
Step 5. level-order: put the root in a queue; pop the front, print it, add its children, repeat.
Step 6. Build a five-node tree and call all four traversals.

Python Program
week13_traversals.py
from collections import deque

class Node:
def __init__(self, data):
[Link] = data
[Link] = None
[Link] = None

def inorder(n):
if n: inorder([Link]); print([Link], end=" "); inorder([Link])
def preorder(n):
if n: print([Link], end=" "); preorder([Link]); preorder([Link])
def postorder(n):
if n: postorder([Link]); postorder([Link]); print([Link], end=" ")

def levelorder(root):

Data Structures with Python (25CS33I) — Lab Manual Page 20


Government Polytechnic Joida (162) Dept of CSE

q = deque([root])
while q:
n = [Link]()
print([Link], end=" ")
if [Link]: [Link]([Link])
if [Link]: [Link]([Link])

root = Node(1)
[Link] = Node(2); [Link] = Node(3)
[Link] = Node(4); [Link] = Node(5)
print("Inorder :", end=" "); inorder(root); print()
print("Preorder :", end=" "); preorder(root); print()
print("Postorder :", end=" "); postorder(root); print()
print("Level-order:", end=" "); levelorder(root); print()

SAMPLE OUTPUT
Inorder : 4 2 5 1 3
Preorder : 1 2 4 5 3
Postorder : 4 5 2 3 1
Level-order: 1 2 3 4 5

TRICK TO REMEMBER THE CODE


The name says where the Root goes: Pre=first, In=middle, Post=last.
Left is always before right. Level-order uses a queue, not recursion.

Data Structures with Python (25CS33I) — Lab Manual Page 21

You might also like