0% found this document useful (0 votes)
20 views19 pages

SLIP's fsemMCA

The document provides Python code snippets for various tasks, including calculating factorials, managing a book and department database in MongoDB, and implementing binary search and merge sort algorithms. It explains the functions for adding, retrieving, updating, and deleting records in the databases, as well as algorithms for sorting and searching. Each section includes code examples and explanations of how the functions work.

Uploaded by

Sarang Tilekar
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)
20 views19 pages

SLIP's fsemMCA

The document provides Python code snippets for various tasks, including calculating factorials, managing a book and department database in MongoDB, and implementing binary search and merge sort algorithms. It explains the functions for adding, retrieving, updating, and deleting records in the databases, as well as algorithms for sorting and searching. Each section includes code examples and explanations of how the functions work.

Uploaded by

Sarang Tilekar
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/ 19

SLIP 1:

I) Python function to calculate the factorial of a number

Here is a Python function that calculates the factorial of a number using a simple recursive approach:

def factorial(n):
# Base case: factorial of 0 or 1 is 1
if n == 0 or n == 1:
return 1
# Recursive case: factorial of n is n * factorial of (n-1)
else:
return n * factorial(n - 1)

# Example usage
num = 5
print(f"The factorial of {num} is {factorial(num)}")

Explanation:

 The function factorial(n) takes an integer n and computes the factorial using recursion.
 If n is 0 or 1, it returns 1 (base case).
 Otherwise, it recursively calls itself with n-1 and multiplies it by n.

II) Creating and managing a Book Database in MongoDB

To interact with MongoDB in Python, we use the pymongo library. Below is an implementation of the
CRUD operations for the BookStoreDB database with two collections: books and authors.

1. Install pymongo if you haven't already:

pip install pymongo

2. MongoDB CRUD operations

from pymongo import MongoClient

# Connect to the MongoDB client


client = MongoClient("mongodb://localhost:27017/") # Adjust the URI if necessary

# Create or select the BookStoreDB database


db = client["BookStoreDB"]

# Create or select collections


books_collection = db["books"]
authors_collection = db["authors"]

# 1. Adding a new book with author details


def add_book(book_title, book_price, author_name, author_birth_year):
# Check if author exists, if not, add to authors collection
author = authors_collection.find_one({"name": author_name})
if not author:
author = {"name": author_name, "birth_year": author_birth_year}
authors_collection.insert_one(author)
# Add book to books collection
book = {
"title": book_title,
"price": book_price,
"author_id": author["_id"] # Reference to the author document
}
books_collection.insert_one(book)
print(f"Book '{book_title}' added successfully.")

# 2. Retrieving all books written by a specific author


def get_books_by_author(author_name):
# Find author details by name
author = authors_collection.find_one({"name": author_name})
if author:
books = books_collection.find({"author_id": author["_id"]})
for book in books:
print(f"Title: {book['title']}, Price: {book['price']}")
else:
print(f"No books found for author {author_name}")

# 3. Updating the price of a book


def update_book_price(book_title, new_price):
result = books_collection.update_one({"title": book_title}, {"$set": {"price":
new_price}})
if result.matched_count > 0:
print(f"Price of the book '{book_title}' updated successfully.")
else:
print(f"Book '{book_title}' not found.")

# 4. Removing a book that is no longer available


def remove_book(book_title):
result = books_collection.delete_one({"title": book_title})
if result.deleted_count > 0:
print(f"Book '{book_title}' removed successfully.")
else:
print(f"Book '{book_title}' not found.")

# Example usage
add_book("The Great Gatsby", 15.99, "F. Scott Fitzgerald", 1896)
get_books_by_author("F. Scott Fitzgerald")
update_book_price("The Great Gatsby", 12.99)
remove_book("The Great Gatsby")

Explanation:

 MongoDB Connection: MongoClient connects to a local MongoDB instance (adjust the URI if
necessary).
 Add a Book: The add_book function checks if the author exists and if not, adds the author. Then,
it adds the book to the books collection.
 Retrieve Books by Author: The get_books_by_author function retrieves and prints all books
by a specific author.
 Update Book Price: The update_book_price function updates the price of a book by its title.
 Remove Book: The remove_book function deletes a book based on its title.

III) Binary Search Algorithm


The binary search algorithm works by repeatedly dividing the search interval in half. If the value of the
search key is less than the value in the middle of the interval, it narrows the interval to the lower half,
otherwise, it narrows it to the upper half.

def binary_search(arr, target):


left, right = 0, len(arr) - 1

while left <= right:


mid = left + (right - left) // 2 # Find the middle index

# Check if target is at the middle


if arr[mid] == target:
return mid
# If target is smaller, ignore the right half
elif arr[mid] > target:
right = mid - 1
# If target is larger, ignore the left half
else:
left = mid + 1

# If we reach here, the element was not present


return -1

# Example usage
arr = [1, 3, 5, 7, 9, 11, 13, 15]
target = 7
result = binary_search(arr, target)

if result != -1:
print(f"Element found at index {result}")
else:
print("Element not found")

Explanation:

 The binary search algorithm works on sorted arrays.


 It divides the array into two halves and determines whether the target value is in the left or right
half.
 If the target is found, it returns the index; otherwise, it returns -1 indicating the element was not
found.
SLIP 2:

Q.1 I) Python function to display the sum of all the elements in a list

To compute the sum of all elements in a list, you can write a simple function using Python's
built-in sum() function or by iterating through the list.

Code Implementation:

def sum_of_elements(lst):
return sum(lst)

# Example usage
numbers = [1, 2, 3, 4, 5]
print(f"The sum of all elements in the list is: {sum_of_elements(numbers)}")

Explanation:

 The sum_of_elements(lst) function uses Python's built-in sum() function to return the
sum of all elements in the list lst.

Q.1 II) Create and manage a Department Database in MongoDB

To implement the CRUD operations in a MongoDB database called CompanyDB with two
collections (departments and employees), we can use the pymongo library in Python.

1. Install pymongo if not already installed:

pip install pymongo

2. MongoDB CRUD operations for Department and Employees

from pymongo import MongoClient

# Connect to MongoDB client (adjust URI as needed)


client = MongoClient("mongodb://localhost:27017/")

# Select or create CompanyDB database


db = client["CompanyDB"]

# Create or select collections


departments_collection = db["departments"]
employees_collection = db["employees"]

# 1. Adding five new departments and assigning employees


def add_departments_with_employees():
departments = [
{"name": "HR", "location": "New York", "employee_ids": []},
{"name": "IT", "location": "San Francisco", "employee_ids": []},
{"name": "Sales", "location": "Chicago", "employee_ids": []},
{"name": "Marketing", "location": "Los Angeles", "employee_ids": []},
{"name": "Finance", "location": "London", "employee_ids": []}
]

# Insert departments into departments collection


department_ids = []
for dept in departments:
result = departments_collection.insert_one(dept)
department_ids.append(result.inserted_id)

# Assign employees to departments


employees = [
{"name": "John Doe", "role": "HR Manager", "department_id":
department_ids[0]},
{"name": "Jane Smith", "role": "Software Engineer", "department_id":
department_ids[1]},
{"name": "Bob Brown", "role": "Sales Executive", "department_id":
department_ids[2]},
{"name": "Alice White", "role": "Marketing Specialist",
"department_id": department_ids[3]},
{"name": "Charlie Black", "role": "Financial Analyst",
"department_id": department_ids[4]}
]

# Insert employees into employees collection


for emp in employees:
employees_collection.insert_one(emp)

# Update department documents to include employee ids


for i, dept_id in enumerate(department_ids):
employees_in_dept = employees_collection.find({"department_id":
dept_id})
employee_ids = [emp["_id"] for emp in employees_in_dept]
departments_collection.update_one({"_id": dept_id}, {"$set":
{"employee_ids": employee_ids}})

print("Departments and employees added successfully.")

# 2. Retrieving all employees in a specific department


def get_employees_by_department(department_name):
department = departments_collection.find_one({"name": department_name})
if department:
employee_ids = department.get("employee_ids", [])
employees = employees_collection.find({"_id": {"$in": employee_ids}})
for emp in employees:
print(f"Name: {emp['name']}, Role: {emp['role']}")
else:
print(f"No department named '{department_name}' found.")

# 3. Updating employee details and deleting a department


def update_employee_details(employee_name, new_role):
result = employees_collection.update_one({"name": employee_name}, {"$set":
{"role": new_role}})
if result.matched_count > 0:
print(f"Employee {employee_name}'s role updated to {new_role}.")
else:
print(f"Employee {employee_name} not found.")

def delete_department(department_name):
department = departments_collection.find_one({"name": department_name})
if department:
department_id = department["_id"]
# Remove employees linked to this department
employees_collection.delete_many({"department_id": department_id})
# Remove the department itself
departments_collection.delete_one({"_id": department_id})
print(f"Department '{department_name}' and its employees removed.")
else:
print(f"Department '{department_name}' not found.")

# Example usage
add_departments_with_employees()
get_employees_by_department("IT")
update_employee_details("John Doe", "Senior HR Manager")
delete_department("Marketing")

Explanation:

 Add Departments with Employees: The add_departments_with_employees function


creates five departments and assigns five employees to them. It first inserts the
departments into the departments collection, then assigns employees to the relevant
departments.
 Retrieve Employees by Department: The get_employees_by_department function
retrieves and prints all employees in a specific department by finding the department and
matching employee department_id.
 Update Employee Details: The update_employee_details function updates an
employee's role in the employees collection based on their name.
 Delete Department: The delete_department function removes a department and its
associated employees from the database.

Q2) Merge Sort Algorithm Implementation

Merge Sort is a divide-and-conquer algorithm. It divides the array into halves, recursively sorts
them, and then merges the sorted halves.

Code Implementation:

def merge_sort(arr):
if len(arr) <= 1:
return arr

# Divide the array into two halves


mid = len(arr) // 2
left_half = merge_sort(arr[:mid])
right_half = merge_sort(arr[mid:])

# Merge the sorted halves


return merge(left_half, right_half)

def merge(left, right):


sorted_list = []
i = j = 0

# Merge the two lists


while i < len(left) and j < len(right):
if left[i] < right[j]:
sorted_list.append(left[i])
i += 1
else:
sorted_list.append(right[j])
j += 1

# Append any remaining elements


sorted_list.extend(left[i:])
sorted_list.extend(right[j:])

return sorted_list

# Example usage
arr = [38, 27, 43, 3, 9, 82, 10]
sorted_arr = merge_sort(arr)
print(f"Sorted array: {sorted_arr}")

Explanation:

 Merge Sort: The merge_sort function recursively splits the array into two halves and
calls merge to merge the sorted halves.
 Merge Function: The merge function takes two sorted arrays and merges them into a
single sorted array.
 Time Complexity: Merge Sort has a time complexity of O(n log n), making it very
efficient for large datasets.
SLIP 3:

Q1 I) Python program to reverse the order of items in an array

You can reverse the order of items in an array in Python using multiple methods, such as list
slicing or the built-in reverse() method. Here's how to do it:

Code Implementation:

def reverse_array(arr):
return arr[::-1] # Using list slicing to reverse the array

# Example usage
arr = [1, 2, 3, 4, 5]
reversed_arr = reverse_array(arr)
print(f"Original array: {arr}")
print(f"Reversed array: {reversed_arr}")

Explanation:

 Reversing the Array: The function reverse_array(arr) reverses the array by using
Python's list slicing arr[::-1].
 Output: The original array is displayed, followed by the reversed array.

Q1 II) Create and manage a Management Database in MongoDB

The task involves creating a MongoDB database called ITCompanyDB with three collections:
managers, projects, and teams. We'll implement CRUD operations for:

 Adding a new project with manager details.


 Listing all projects handled by a specific manager.
 Updating team composition for a project.
 Deleting a project once completed.

MongoDB CRUD Operations Code:

from pymongo import MongoClient

# Connect to MongoDB client (adjust URI as needed)


client = MongoClient("mongodb://localhost:27017/")

# Select or create ITCompanyDB database


db = client["ITCompanyDB"]

# Create or select collections


managers_collection = db["managers"]
projects_collection = db["projects"]
teams_collection = db["teams"]

# 1. Adding a new project with manager details


def add_project(project_name, manager_name, manager_contact):
# Add manager to managers collection if not already present
manager = managers_collection.find_one({"name": manager_name})
if not manager:
manager = {"name": manager_name, "contact": manager_contact}
result = managers_collection.insert_one(manager)
manager_id = result.inserted_id
else:
manager_id = manager["_id"]

# Add project to projects collection


project = {"name": project_name, "manager_id": manager_id, "team_ids": []}
result = projects_collection.insert_one(project)
print(f"Project '{project_name}' added successfully with manager
'{manager_name}'.")

# 2. Listing all projects handled by a specific manager


def list_projects_by_manager(manager_name):
manager = managers_collection.find_one({"name": manager_name})
if manager:
projects = projects_collection.find({"manager_id": manager["_id"]})
for project in projects:
print(f"Project Name: {project['name']}")
else:
print(f"No manager found with the name '{manager_name}'.")

# 3. Updating team composition for a project


def update_team_composition(project_name, team_member_names):
project = projects_collection.find_one({"name": project_name})
if project:
# Add team members to teams collection and link them to the project
team_ids = []
for member in team_member_names:
team = {"name": member, "project_id": project["_id"]}
team_result = teams_collection.insert_one(team)
team_ids.append(team_result.inserted_id)

# Update project with new team members


projects_collection.update_one({"_id": project["_id"]}, {"$set":
{"team_ids": team_ids}})
print(f"Team composition for project '{project_name}' updated.")
else:
print(f"Project '{project_name}' not found.")

# 4. Deleting a project once completed


def delete_project(project_name):
project = projects_collection.find_one({"name": project_name})
if project:
# Remove associated team members
teams_collection.delete_many({"project_id": project["_id"]})
# Delete the project
projects_collection.delete_one({"_id": project["_id"]})
print(f"Project '{project_name}' and associated team members removed
successfully.")
else:
print(f"Project '{project_name}' not found.")

# Example usage
add_project("Project A", "Alice", "[email protected]")
add_project("Project B", "Bob", "[email protected]")
list_projects_by_manager("Alice")
update_team_composition("Project A", ["John", "Sara", "Tom"])
delete_project("Project B")

Explanation:

1. Add Project with Manager:


o The function add_project adds a new project. It checks if the manager exists in
the managers collection and inserts the manager if necessary. It then associates
the manager with the project and adds it to the projects collection.
2. List Projects by Manager:
o The list_projects_by_manager function retrieves all projects associated with a
specific manager by using the manager's ID.
3. Update Team Composition:
o The update_team_composition function adds team members to the teams
collection and links them to the specified project. It updates the team_ids in the
project document.
4. Delete Project:
o The delete_project function removes the project and its associated team
members from the database.

Q2) Binary Search Algorithm Implementation

To implement binary search, we will assume that the array is sorted. The binary search algorithm
repeatedly divides the search space in half.

Code Implementation:

def binary_search(arr, target):


left, right = 0, len(arr) - 1

while left <= right:


mid = left + (right - left) // 2 # Find the middle index

# Check if target is at the middle


if arr[mid] == target:
return mid
# If target is smaller, ignore the right half
elif arr[mid] > target:
right = mid - 1
# If target is larger, ignore the left half
else:
left = mid + 1

# If we reach here, the element was not present


return -1

# Example usage
arr = [10, 20, 30, 40, 50, 60, 70]
target = 40
result = binary_search(arr, target)

if result != -1:
print(f"Element found at index {result}")
else:
print("Element not found")

Explanation:

 Binary Search: The function binary_search splits the array into two halves and checks
if the middle element is the target. If not, it continues searching in the appropriate half.
 Time Complexity: The time complexity of binary search is O(log n), making it efficient
for large sorted arrays.
SLIP 4:

I) Python program to get the number of occurrences of specified elements in an


array

In Python, you can count the occurrences of an element in a list (array) using the count()
method or by utilizing the collections.Counter class. Here's how you can implement both
methods:

Code Implementation:

from collections import Counter

# Method 1: Using the list count() method


def count_occurrences(arr, element):
return arr.count(element)

# Method 2: Using collections.Counter to count all elements


def count_all_occurrences(arr):
return dict(Counter(arr))

# Example usage
arr = [1, 2, 2, 3, 4, 2, 5, 6, 2]
element = 2

print(f"The element {element} occurs {count_occurrences(arr, element)} times


in the array.")
print(f"All element occurrences: {count_all_occurrences(arr)}")

Explanation:

 count_occurrences Function: Uses the count() method on the array to return the
number of times the specified element appears.
 count_all_occurrences Function: Uses Counter from the collections module to
count the occurrences of all elements in the list and return them as a dictionary.
 Example Output:
 The element 2 occurs 4 times in the array.
 All element occurrences: {1: 1, 2: 4, 3: 1, 4: 1, 5: 1, 6: 1}

II) Create and manage a Courses Database in MongoDB

The task is to manage a MongoDB database called CoursesDB with two collections: courses
(storing course details) and students (storing a list of students enrolled in each course). We will
implement CRUD operations for:

1. Adding five new courses.


2. Retrieving students enrolled in a specific course.
3. Updating course duration.
4. Deleting a course that is no longer offered.

MongoDB CRUD Operations Code:

from pymongo import MongoClient

# Connect to MongoDB client (adjust URI as needed)


client = MongoClient("mongodb://localhost:27017/")

# Select or create CoursesDB database


db = client["CoursesDB"]

# Create or select collections


courses_collection = db["courses"]
students_collection = db["students"]

# 1. Adding five new courses


def add_courses():
courses = [
{"course_name": "Data Science", "duration": "6 months", "student_ids":
[]},
{"course_name": "Web Development", "duration": "4 months",
"student_ids": []},
{"course_name": "Machine Learning", "duration": "6 months",
"student_ids": []},
{"course_name": "Digital Marketing", "duration": "3 months",
"student_ids": []},
{"course_name": "Cloud Computing", "duration": "5 months",
"student_ids": []}
]

# Insert courses into the courses collection


for course in courses:
courses_collection.insert_one(course)
print("5 new courses added successfully.")

# 2. Retrieving students enrolled in a specific course


def get_students_enrolled(course_name):
course = courses_collection.find_one({"course_name": course_name})
if course:
student_ids = course.get("student_ids", [])
students = students_collection.find({"_id": {"$in": student_ids}})
for student in students:
print(f"Student: {student['name']}, Email: {student['email']}")
else:
print(f"No course found with the name '{course_name}'.")

# 3. Updating course duration


def update_course_duration(course_name, new_duration):
result = courses_collection.update_one({"course_name": course_name},
{"$set": {"duration": new_duration}})
if result.matched_count > 0:
print(f"Course duration for '{course_name}' updated to
{new_duration}.")
else:
print(f"Course '{course_name}' not found.")

# 4. Deleting a course no longer offered


def delete_course(course_name):
course = courses_collection.find_one({"course_name": course_name})
if course:
# Remove all students enrolled in the course
courses_collection.delete_one({"course_name": course_name})
print(f"Course '{course_name}' deleted successfully.")
else:
print(f"Course '{course_name}' not found.")

# Example usage
add_courses()

# Add students and enroll them in courses (You can create students in the
'students' collection as needed)
students_collection.insert_many([
{"name": "John Doe", "email": "[email protected]"},
{"name": "Alice Smith", "email": "[email protected]"},
{"name": "Bob Brown", "email": "[email protected]"}
])

# Enroll students in courses


course = courses_collection.find_one({"course_name": "Data Science"})
students_collection.update_one({"name": "John Doe"}, {"$set": {"enrolled_in":
course["_id"]}})
students_collection.update_one({"name": "Alice Smith"}, {"$set":
{"enrolled_in": course["_id"]}})
courses_collection.update_one({"course_name": "Data Science"}, {"$push":
{"student_ids": course["_id"]}})

# Retrieve students in "Data Science"


get_students_enrolled("Data Science")

# Update course duration


update_course_duration("Web Development", "5 months")

# Delete course
delete_course("Cloud Computing")

Explanation:

1. Add Courses:
o The add_courses function adds five courses to the courses collection with
default values for course name, duration, and an empty list for enrolled students.
2. Get Students Enrolled:
o The get_students_enrolled function retrieves the students who are enrolled in
a particular course. It finds the course document and then uses the student_ids
array to fetch the enrolled students from the students collection.
3. Update Course Duration:
o The update_course_duration function updates the duration of a course in the
courses collection by specifying the course name and the new duration.
4. Delete Course:
o The delete_course function deletes a course from the courses collection,
effectively removing it from the list of available courses.

Q2) Linear Search Algorithm Implementation

Linear search is a simple search algorithm where each element in the list is checked in sequence
until the target is found.

Code Implementation:

def linear_search(arr, target):


for index, element in enumerate(arr):
if element == target:
return index # Return the index of the target element
return -1 # Return -1 if the element is not found

# Example usage
arr = [10, 20, 30, 40, 50, 60, 70]
target = 40
result = linear_search(arr, target)

if result != -1:
print(f"Element {target} found at index {result}")
else:
print(f"Element {target} not found")

Explanation:

 Linear Search: The function linear_search iterates through each element in the array
arr and compares it to the target. If the target is found, it returns the index of that
element. If not, it returns -1 indicating the target was not found.
 Time Complexity: The time complexity of linear search is O(n), where n is the number
of elements in the array.
SLIP 5:

Let's break down the tasks into separate solutions for each question.

Q1: Python Program to Accept and Convert String in Uppercase or Vice Versa

Here is a Python program that accepts a string and converts it to uppercase or lowercase based on
the user's input.

def convert_string():
# Accept the input string from the user
input_string = input("Enter a string: ")

# Ask the user whether they want to convert to uppercase or lowercase


choice = input("Do you want to convert to uppercase or lowercase? (Enter
'U' for uppercase, 'L' for lowercase): ").strip().upper()

# Convert the string based on user choice


if choice == 'U':
print("Converted string in uppercase:", input_string.upper())
elif choice == 'L':
print("Converted string in lowercase:", input_string.lower())
else:
print("Invalid choice! Please enter 'U' or 'L'.")

# Call the function


convert_string()

Q2: Company Database in MongoDB with CRUD Operations

First, you need to have MongoDB installed and running on your system. You can use pymongo to
interact with MongoDB from Python.

1. Install pymongo if you don't have it already:

pip install pymongo

2. Python Program for CRUD Operations in MongoDB

from pymongo import MongoClient

# Connect to MongoDB
client = MongoClient("mongodb://localhost:27017/")
db = client.CompanyDB # Use the CompanyDB database
companies_collection = db.companies # Collection for company details
employees_collection = db.employees # Collection for employee details

# Function to add a new company and its employees


def add_company(company_name, location, employees):
company = {
"company_name": company_name,
"location": location
}
# Insert the company document
company_id = companies_collection.insert_one(company).inserted_id

# Add employees to the employee collection with company reference


for employee in employees:
employee["company_id"] = company_id
employees_collection.insert_one(employee)
print(f"Company {company_name} and its employees added.")

# Function to list all employees in a specific company


def list_employees_by_company(company_name):
company = companies_collection.find_one({"company_name": company_name})
if company:
company_id = company["_id"]
employees = employees_collection.find({"company_id": company_id})
for emp in employees:
print(emp)
else:
print(f"Company {company_name} not found.")

# Function to update a company's location


def update_company_location(company_name, new_location):
result = companies_collection.update_one(
{"company_name": company_name},
{"$set": {"location": new_location}}
)
if result.matched_count > 0:
print(f"Company {company_name}'s location updated to {new_location}.")
else:
print(f"Company {company_name} not found.")

# Function to delete a company


def delete_company(company_name):
company = companies_collection.find_one({"company_name": company_name})
if company:
company_id = company["_id"]
# First, delete all employees associated with the company
employees_collection.delete_many({"company_id": company_id})
# Then delete the company itself
companies_collection.delete_one({"company_name": company_name})
print(f"Company {company_name} and its employees have been deleted.")
else:
print(f"Company {company_name} not found.")

# Example Usage:
# Add a company and its employees
add_company(
"TechCorp",
"New York",
[{"name": "Alice", "position": "Developer"}, {"name": "Bob", "position":
"Manager"}]
)

# List all employees in TechCorp


list_employees_by_company("TechCorp")

# Update the location of TechCorp


update_company_location("TechCorp", "San Francisco")

# Delete TechCorp
delete_company("TechCorp")

In the code above:

 We use pymongo.MongoClient to connect to the MongoDB server and create a database


CompanyDB with two collections: companies and employees.
 The CRUD operations include:
o Adding a new company and its employees.
o Listing employees of a specific company.
o Updating a company's location.
o Deleting a company and its employees.

Q3: Dynamic Implementation of Singly Linked List

Here’s a Python program for the dynamic implementation of a Singly Linked List with
operations like Create, Insert, Delete, Display, and Search.

class Node:
def __init__(self, data):
self.data = data # Data of the node
self.next = None # Pointer to the next node

class SinglyLinkedList:
def __init__(self):
self.head = None # Initialize head as None

# Create a new node and append it at the end


def insert_end(self, data):
new_node = Node(data)
if self.head is None:
self.head = new_node
return
last = self.head
while last.next:
last = last.next
last.next = new_node

# Insert at the beginning


def insert_start(self, data):
new_node = Node(data)
new_node.next = self.head
self.head = new_node

# Delete a node by value


def delete(self, value):
current = self.head
if current and current.data == value:
self.head = current.next
current = None
return
prev = None
while current and current.data != value:
prev = current
current = current.next
if current is None:
print(f"Value {value} not found.")
return
prev.next = current.next
current = None

# Display the list


def display(self):
current = self.head
if not current:
print("List is empty.")
return
while current:
print(current.data, end=" -> ")
current = current.next
print("None")

# Search for a value in the list


def search(self, value):
current = self.head
while current:
if current.data == value:
print(f"Value {value} found.")
return
current = current.next
print(f"Value {value} not found.")

# Example usage:
ll = SinglyLinkedList()
ll.insert_end(10)
ll.insert_end(20)
ll.insert_start(5)
ll.display() # 5 -> 10 -> 20 -> None
ll.search(10) # Value 10 found.
ll.delete(10)
ll.display() # 5 -> 20 -> None
ll.search(10) # Value 10 not found.

You might also like