DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND
MACHINE LEARNING
SEMESTER: III
COURSE CODE: 22AM302
COURSE NAME: DATA STRUCTURES-I
LIST OF EXPERIMENTS - OUTCOME BASED LAB TASK
DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND MACHINE LEARNING
Vision of the Department
To achieve excellence in the field of Artificial Intelligence and Machine Learning by focusing
on knowledge-centric education systems, integrative partnerships, innovation and cutting-edge
research to meet latest industry standards and service the greater cause of society.
Mission of the Department
M1. To develop professionals skilled in the field of Artificial Intelligence and Machine
Learning.
M2. To impart quality and value-based education and contribute towards the innovation of
computing, expert systems, AI, ML to solve complex problems in research and society
Program Outcomes (POs)
Engineering Graduates will be able to:
PO1. Engineering knowledge: Apply the knowledge of mathematics, science, engineering
fundamentals, and an engineering specialization to the solution of complex engineering
problems.
PO2. Problem analysis: Identify, formulate, review research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles of mathematics,
natural sciences, and engineering sciences.
PO3. Design/development of solutions: Design solutions for complex engineering problems
and design system components or processes that meet the specified needs with appropriate
consideration for the public health and safety, and the cultural, societal, and environmental
considerations.
PO4. Conduct investigations of complex problems: Use research-based knowledge and
research methods including design of experiments, analysis and interpretation of data, and
synthesis of the information to provide valid conclusions.
PO5. Modern tool usage: Create, select, and apply appropriate techniques, resources, and
modern engineering and IT tools including prediction and modeling to complex engineering
activities with an understanding of the limitations.
PO6. The engineer and society: Apply reasoning informed by the contextual knowledge to
assess societal, health, safety, legal and cultural issues and the consequent responsibilities
relevant to the professional engineering practice.
PO7. Environment and sustainability: Understand the impact of the professional engineering
solutions in societal and environmental contexts, and demonstrate the knowledge of, and need
for sustainable development.
PO8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities
and norms of the engineering practice.
PO9. Individual and team work: Function effectively as an individual, and as a member or
leader in diverse teams, and in multidisciplinary settings.
PO10. Communication: Communicate effectively on complex engineering activities with the
engineering community and with society at large, such as, being able to comprehend and write
effective reports and design documentation, make effective presentations, and give and receive
clear instructions.
PO11. Project management and finance: Demonstrate knowledge and understanding of the
engineering and management principles and apply these to one’s own work, as a member and
leader in a team, to manage projects and in multidisciplinary environments.
PO12. Life-long learning: Recognize the need for, and have the preparation and ability to
engage in independent and life-long learning in the broadest context of technological change.
Program Specific Outcomes (PSOs)
Engineering Graduates will be able to:
PSO1. Develop models in Data Science, Machine learning, deep learning and Big data
technologies, using AI and modern tools.
PSO2. Formulate solutions for interdisciplinary AI problems through acquired programming
knowledge in the respective domains fulfilling with real-time constraints.
DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND MACHINE LEARNING
SEMESTER: III
COURSE CODE: 22AM302
COURSE NAME: DATA STRUCTURES-I
LIST OF EXPERIMENTS - OUTCOME BASED LAB TASK
S. No. Name of the Experiment
1 Implement a python program for the supermarket application using Stack and
Queue for basket storage and checkout respectively.
2 Implement a python program for using a singly linked list. managing a train
station and need to keep track of passengers on a particular train.
3 Create a python program that allows users to search for a person's phone
number quickly in the phone directory.
4 Implement a Python program to sort the student grades for the quiz competition.
Implement a digital signature generator and verifier using hash functions and
5 public-key cryptography. Users can sign documents and verify the authenticity
of signed documents.
6 Implement a python program to give a direction for a Stranger. Landmark will be
considered as a node and the path between the two landmark is the link.
Experiment 1
Implement a python program for the supermarket application using Stack and Queue for
basket storage and checkout respectively.
Aim:
To implement a Python program for a supermarket application using Stack for basket storage and
Queue for checkout management.
Algorithm:
1. Define Stack (Basket Storage):
o Implement push operation to add items.
o Implement pop operation to remove items.
o Implement display operation to show the basket contents.
2. Define Queue (Checkout System):
o Implement enqueue operation to add customers to checkout.
o Implement dequeue operation to process customers.
o Implement display operation to show the queue.
3. Simulate Customer Shopping:
o Allow customers to add/remove items in the basket (Stack).
o Allow customers to proceed to checkout (Queue).
4. Simulate Checkout Process:
o Process customers in a First-In-First-Out (FIFO) manner.
o Display processed customers.
Program:
from collections import deque
# Stack Implementation for Basket Storage
class Basket:
def __init__(self):
self.stack = []
def add_item(self, item):
self.stack.append(item)
print(f"Added {item} to basket.")
def remove_item(self):
if self.stack:
item = self.stack.pop()
print(f"Removed {item} from basket.")
else:
print("Basket is empty!")
def view_basket(self):
if self.stack:
print("Basket items:", self.stack)
else:
print("Basket is empty!")
# Queue Implementation for Checkout
class CheckoutQueue:
def __init__(self):
self.queue = deque()
def join_queue(self, customer_name):
self.queue.append(customer_name)
print(f"{customer_name} joined the checkout queue.")
def process_customer(self):
if self.queue:
customer = self.queue.popleft()
print(f"{customer} has been checked out.")
else:
print("No customers in queue!")
def view_queue(self):
if self.queue:
print("Checkout queue:", list(self.queue))
else:
print("Queue is empty!")
# Simulating the Supermarket Application
basket = Basket()
checkout = CheckoutQueue()
# Customer actions
basket.add_item("Milk")
basket.add_item("Bread")
basket.view_basket()
basket.remove_item()
basket.view_basket()
# Checkout process
checkout.join_queue("Customer1")
checkout.join_queue("Customer2")
checkout.view_queue()
checkout.process_customer()
checkout.view_queue()
OUTPUT:
Added Milk to basket.
Added Bread to basket.
Basket items: ['Milk', 'Bread']
Removed Bread from basket.
Basket items: ['Milk']
Customer1 joined the checkout queue.
Customer2 joined the checkout queue.
Checkout queue: ['Customer1', 'Customer2']
Customer1 has been checked out.
Checkout queue: ['Customer2']
Result:
Thus, the program has been implemented Successfully.
Experiment 2
Implement a python program for using a singly linked list. managing a train station and need
to keep track of passengers on a particular train.
Aim:
To implement a Python program using a Singly Linked List for managing passengers on a train at a
station.
Algorithm:
1. Define a Node class to represent a passenger (with attributes like name and ticket number).
2. Implement a Singly Linked List (TrainPassengerList) with operations:
3. Add a new passenger to the list.
4. Remove a passenger from the list.
5. Display the list of passengers.
6. Simulate passenger management:
7. Add multiple passengers.
8. Remove specific passengers.
9. Display current passenger details.
Program:
# Node class to represent a Passenger
class PassengerNode:
def __init__(self, name, ticket_number):
self.name = name
self.ticket_number = ticket_number
self.next = None # Pointer to next node
# Singly Linked List to manage train passengers
class TrainPassengerList:
def __init__(self):
self.head = None # Initialize empty list
# Add a passenger to the train (Append at end)
def add_passenger(self, name, ticket_number):
new_passenger = PassengerNode(name, ticket_number)
if self.head is None:
self.head = new_passenger
else:
temp = self.head
while temp.next:
temp = temp.next
temp.next = new_passenger
print(f"Passenger {name} (Ticket No: {ticket_number}) added.")
# Remove a passenger by ticket number
def remove_passenger(self, ticket_number):
if self.head is None:
print("No passengers to remove.")
return
# If head is the passenger to be removed
if self.head.ticket_number == ticket_number:
print(f"Passenger {self.head.name} (Ticket No: {ticket_number}) removed.")
self.head = self.head.next
return
# Searching for the passenger in the list
prev = None
current = self.head
while current and current.ticket_number != ticket_number:
prev = current
current = current.next
if current is None:
print(f"No passenger found with Ticket No: {ticket_number}")
else:
prev.next = current.next
print(f"Passenger {current.name} (Ticket No: {ticket_number}) removed.")
# Display all passengers in the train
def display_passengers(self):
if self.head is None:
print("No passengers on the train.")
return
temp = self.head
print("Current passengers on the train:")
while temp:
print(f"Name: {temp.name}, Ticket No: {temp.ticket_number}")
temp = temp.next
# Simulating Train Passenger Management
train = TrainPassengerList()
# Adding passengers
train.add_passenger("Alice", 101)
train.add_passenger("Bob", 102)
train.add_passenger("Charlie", 103)
# Displaying passengers
train.display_passengers()
# Removing a passenger
train.remove_passenger(102)
# Displaying passengers after removal
train.display_passengers()
OUTPUT:
Passenger Alice (Ticket No: 101) added.
Passenger Bob (Ticket No: 102) added.
Passenger Charlie (Ticket No: 103) added.
Current passengers on the train:
Name: Alice, Ticket No: 101
Name: Bob, Ticket No: 102
Name: Charlie, Ticket No: 103
Passenger Bob (Ticket No: 102) removed.
Current passengers on the train:
Name: Alice, Ticket No: 101
Name: Charlie, Ticket No: 103
Result:
Thus the program has been completed successfully.
Experiment 3
Create a python program that allows users to search for a person's phone number quickly in
the phone directory.
Aim:
To implement a Python program that allows users to search for a person's phone number quickly in a
phone directory using a dictionary (hash map).
Algorithm:
• Create a dictionary to store names as keys and phone numbers as values.
• Allow users to:
• Add new contacts.
• Search for a contact by name.
• Delete a contact.
• Display all contacts.
• Provide an interactive menu for user input.
Program:
# Phone Directory using a Dictionary (Hash Map)
class PhoneDirectory:
def __init__(self):
self.directory = {}
# Add a contact
def add_contact(self, name, phone_number):
self.directory[name.lower()] = phone_number
print(f"Contact {name} added successfully.")
# Search for a contact
def search_contact(self, name):
name_lower = name.lower()
if name_lower in self.directory:
print(f"{name}: {self.directory[name_lower]}")
else:
print(f"Contact {name} not found.")
# Delete a contact
def delete_contact(self, name):
name_lower = name.lower()
if name_lower in self.directory:
del self.directory[name_lower]
print(f"Contact {name} deleted successfully.")
else:
print(f"Contact {name} not found.")
# Display all contacts
def display_contacts(self):
if not self.directory:
print("Phone directory is empty.")
return
print("Phone Directory:")
for name, phone in sorted(self.directory.items()):
print(f"{name.title()}: {phone}")
# Menu-driven program
def main():
phone_directory = PhoneDirectory()
while True:
print("\nPhone Directory Menu:")
print("1. Add Contact")
print("2. Search Contact")
print("3. Delete Contact")
print("4. Display All Contacts")
print("5. Exit")
choice = input("Enter your choice: ")
if choice == '1':
name = input("Enter contact name: ")
phone_number = input("Enter phone number: ")
phone_directory.add_contact(name, phone_number)
elif choice == '2':
name = input("Enter name to search: ")
phone_directory.search_contact(name)
elif choice == '3':
name = input("Enter name to delete: ")
phone_directory.delete_contact(name)
elif choice == '4':
phone_directory.display_contacts()
elif choice == '5':
print("Exiting Phone Directory. Goodbye!")
break
else:
print("Invalid choice. Please try again.")
# Run the program
if __name__ == "__main__":
main()
OUTPUT
Phone Directory Menu:
1. Add Contact
2. Search Contact
3. Delete Contact
4. Display All Contacts
5. Exit
Enter your choice: 1
Enter contact name: Alice
Enter phone number: 9876543210
Contact Alice added successfully.
Enter your choice: 1
Enter contact name: Bob
Enter phone number: 9123456789
Contact Bob added successfully.
Enter your choice: 4
Phone Directory:
Alice: 9876543210
Bob: 9123456789
Enter your choice: 2
Enter name to search: Alice
Alice: 9876543210
Enter your choice: 3
Enter name to delete: Bob
Contact Bob deleted successfully.
Enter your choice: 4
Phone Directory:
Alice: 9876543210
Enter your choice: 5
Exiting Phone Directory. Goodbye!
Result:
Thus the Program executed Successfully.
Experiment 4
Implement a Python program to sort the student grades for the quiz competition.
Aim:
To implement a Python program to sort student grades for a quiz competition.
Algorithm:
• Accept student details (name and grade).
• Sort the student grades in descending order (highest to lowest).
• Display the sorted list with student names and grades.
Program:
# Function to sort students based on grades using Bubble Sort
def bubble_sort(students):
n = len(students)
for i in range(n):
for j in range(0, n-i-1):
if students[j][1] < students[j+1][1]: # Sort in descending order
students[j], students[j+1] = students[j+1], students[j]
# Function to display students and their grades
def display_students(students):
print("\nSorted Student Grades (Highest to Lowest):")
for student, grade in students:
print(f"{student}: {grade}")
# Main program
students = []
n = int(input("Enter the number of students: "))
# Getting student details
for _ in range(n):
name = input("Enter student name: ")
grade = float(input("Enter grade: "))
students.append((name, grade))
# Sorting students based on grades
bubble_sort(students)
# Displaying sorted student grades
display_students(students)
OUTPUT
Enter the number of students: 4
Enter student name: Alice
Enter grade: 85
Enter student name: Bob
Enter grade: 92
Enter student name: Charlie
Enter grade: 78
Enter student name: David
Enter grade: 88
Sorted Student Grades (Highest to Lowest):
Bob: 92.0
David: 88.0
Alice: 85.0
Charlie: 78.0
Result:
Thus the program has been implemented successfully.
Experiment 5
Implement a digital signature generator and verifier using hash functions and public-key
cryptography. Users can sign documents and verify the authenticity of signed documents.
Aim:
To implement a Python program for a digital signature generator and verifier using hash functions
(SHA-256) and public-key cryptography (RSA).
Algorithm:
• Signature Generation:
1. Generate an RSA key pair (public & private keys).
2. Read the document and compute its hash using SHA-256.
3. Sign the hash using the private key.
4. Store the signature along with the document.
• Signature Verification:
1. Read the signed document and extract the signature.
2. Compute the document’s hash using SHA-256.
3. Verify the signature using the public key.
4. If valid, display "Signature Verified.", otherwise display "Signature Invalid!".
Program:
from Crypto.PublicKey import RSA
from Crypto.Signature import pkcs1_15
from Crypto.Hash import SHA256
# Generate RSA key pair
def generate_keys():
key = RSA.generate(2048) # Generate a 2048-bit RSA key pair
private_key = key.export_key()
public_key = key.publickey().export_key()
# Save keys to files
with open("private.pem", "wb") as priv_file:
priv_file.write(private_key)
with open("public.pem", "wb") as pub_file:
pub_file.write(public_key)
print("Keys generated successfully!")
# Sign a document
def sign_document(filename):
# Load private key
with open("private.pem", "rb") as priv_file:
private_key = RSA.import_key(priv_file.read())
# Read document content
with open(filename, "rb") as file:
data = file.read()
# Hash the document
hash_value = SHA256.new(data)
# Sign the hash
signature = pkcs1_15.new(private_key).sign(hash_value)
# Save signature to a file
with open("signature.sig", "wb") as sig_file:
sig_file.write(signature)
print("Document signed successfully!")
# Verify a document's signature
def verify_signature(filename):
# Load public key
with open("public.pem", "rb") as pub_file:
public_key = RSA.import_key(pub_file.read())
# Read document content
with open(filename, "rb") as file:
data = file.read()
# Read signature
with open("signature.sig", "rb") as sig_file:
signature = sig_file.read()
# Hash the document
hash_value = SHA256.new(data)
# Verify signature
try:
pkcs1_15.new(public_key).verify(hash_value, signature)
print("Signature Verified. Document is Authentic!")
except (ValueError, TypeError):
print("Signature Invalid! Document may have been altered.")
# Main menu
def main():
while True:
print("\nDigital Signature System")
print("1. Generate RSA Keys")
print("2. Sign a Document")
print("3. Verify a Document")
print("4. Exit")
choice = input("Enter your choice: ")
if choice == '1':
generate_keys()
elif choice == '2':
filename = input("Enter document filename to sign: ")
sign_document(filename)
elif choice == '3':
filename = input("Enter document filename to verify: ")
verify_signature(filename)
elif choice == '4':
print("Exiting Digital Signature System. Goodbye!")
break
else:
print("Invalid choice. Please try again.")
# Run the program
if __name__ == "__main__":
main()
OUTPUT
Step 1: Generate Keys
Digital Signature System
1. Generate RSA Keys
2. Sign a Document
3. Verify a Document
4. Exit
Enter your choice: 1
Keys generated successfully!
Step 2: Sign a Document
Enter document filename to sign: sample.txt
Document signed successfully!
Step 3: Verify Signature
Enter document filename to verify: sample.txt
Signature Verified. Document is Authentic!
Result:
Thus, the Program was implemented successfully.
Experiment 6
Implement a python program to give a direction for a Stranger. Landmark will be considered
as a node and the path between the two landmark is the link.
Aim:
To implement a Python program that provides directions to a stranger using a Tree data structure
Algorithm:
• Create a Tree structure where landmarks are nodes, and paths are edges.
• Add child landmarks to their respective parent nodes.
• Implement a Depth-First Search (DFS) or Breadth-First Search (BFS) to find the path
between two landmarks.
• Display the directional path from the starting landmark to the destination.
Program:
class Landmark:
def __init__(self, name):
self.name = name
self.children = [] # Adjacent landmarks (sub-paths)
def add_path(self, child):
self.children.append(child)
# Function to perform DFS to find path between landmarks
def find_path(root, destination, path=None):
if path is None:
path = []
path.append(root.name)
if root.name == destination:
return path
for child in root.children:
new_path = find_path(child, destination, path.copy())
if new_path:
return new_path
return None
# Creating the landmark tree structure
root = Landmark("Train Station")
landmark1 = Landmark("City Square")
landmark2 = Landmark("Mall")
landmark3 = Landmark("Park")
landmark4 = Landmark("Museum")
landmark5 = Landmark("Library")
landmark6 = Landmark("University")
landmark7 = Landmark("Hospital")
# Establishing paths (tree structure)
root.add_path(landmark1)
root.add_path(landmark2)
landmark1.add_path(landmark3)
landmark1.add_path(landmark4)
landmark2.add_path(landmark5)
landmark2.add_path(landmark6)
landmark3.add_path(landmark7)
# User input for navigation
start = "Train Station"
destination = input("Enter destination landmark: ")
# Find and display path
path = find_path(root, destination)
if path:
print("\nDirection from {} to {}:".format(start, destination))
print(" → ".join(path))
else:
print("Destination not found in the given structure.")
OUTPUT
Enter destination landmark: Museum
Direction from Train Station to Museum:
Train Station → City Square → Museum
Result:
Thus the program was implemented successfully.