PP-4 MS
PP-4 MS
OR
(B) Write a Python program to check if a string is a palindrome (reads the same
backward as forward). The string should be entered by the user.
Ans.
def is_palindrome(text):
processed_text = text[::-1]
return processed_text
Ans.
def add_product(RecentlyViewed, new_product):
RecentlyViewed.append(new_product)
def remove_product(RecentlyViewed):
if RecentlyViewed:
return RecentlyViewed.pop()
else:
print("No products recently viewed.")
def show_latest_product(RecentlyViewed):
if RecentlyViewed:
print(RecentlyViewed[-1])
else:
print("No products recently viewed.")
OR
(B)
A hospital is managing patient data using a stack-based system. Patient records
are initially stored in a list. Each record is a tuple containing (patient_id, age,
priority_level). Priority levels are integers, with higher numbers representing
higher priority.
(I) Create a list named patients containing the following patient records:
(101, 65, 2), (102, 32, 4), (103, 78, 1), (104, 45, 3), (105, 52, 5), (106, 28, 2)
(II) Write the definition of a user-defined function push_high_priority(patients,
priority_threshold). It should push only those patient records with a priority level
greater than or equal to the priority_threshold onto a stack called
high_priority_patients.
(III) Write a function get_high_priority() to display all elements of the
high_priority_patients stack while deleting them one by one. If the stack is empty,
the function should display No high-priority patients.
Ans.
# (I) Create the list of patient records
patients = [(101, 65, 2), (102, 32, 4), (103, 78, 1), (104, 45, 3),
(105, 52, 5), (106, 28, 2)]
(ii) Display all data separated by Department and in decreasing order of Salary:
SELECT * FROM Faculty ORDER BY Department, Salary DESC;
OR
(B)
(i) Display Gender wise average salary of those faculties with average salary more
than 90000:
SELECT Gender, AVG(Salary) as AvgSalary FROM Faculty
GROUP BY Gender HAVING AVG(Salary) > 90000;
(ii) Display FName and F_ID of faculties having the string 'ta' in the Fname:
SELECT FName, F_ID FROM Faculty WHERE FName LIKE '%ta%';
(ii) process_data("abc")
Output:
Invalid input: Not an integer.
Data processing complete.
(iii) process_data(50)
Output:
Value is not greater than 100.
Data processing complete.
33 A librarian is managing book inventory using a CSV file named `Inventory.csv`. 4
The file structure is: `[BookID, Title, Author, Available]` where `BookID` is an
integer, `Title` and `Author` are strings, and `Available` is an integer representing
the number of copies available.
The librarian needs to write the following functions:
- add_book(): This function accepts new book details from the user and adds
them to `Inventory.csv`. The file should be created with column headers if it
doesn't exist.
- check_availability(book_id): This function takes a `book_id` as input and
returns the number of copies available for that book. If the book is not
found, it should return -1.
Ans.
import csv
import os
def add_book():
file_exists = os.path.isfile('Inventory.csv')
with open('Inventory.csv', 'a', newline='') as file:
writer = csv.writer(file)
if not file_exists:
writer.writerow(['BookID', 'Title', 'Author', 'Available'])
book_id = input("Enter BookID: ")
title = input("Enter Title: ")
author = input("Enter Author: ")
available = input("Enter number of copies available: ")
writer.writerow([book_id, title, author, available])
print("Book added successfully!")
def check_availability(book_id):
try:
with open('Inventory.csv', 'r') as file:
reader = csv.DictReader(file)
for row in reader:
if row['BookID'] == str(book_id):
return int(row['Available'])
except FileNotFoundError:
print("Inventory file not found.")
return -1
34 Give output of the following queries as per given table(s): 4
WORKER
WID WNAME JOB SALARY DNO
1001 RAHUL SHARMA CLERK 15000 D03
1002 MUKESH VYAS ELECTRICIAN 11000 D01
1003 SURESH FITTER 9000 D02
1004 ANKUR GUARD 8000 D01
DEPT
DNO DNAME LOC MANAGER
D01 PRODUCTION GROUND FLOOR
D K JAIN
D02 ACCOUNTS 1ST FLOOR
S ARORA
D03 SECURITY 1ST FLOOR
R K SINGH
Ans.
(i) SELECT DISTINCT JOB FROM WORKER;
JOB
----
CLERK
ELECTRICIAN
FITTER
GUARD
(ii) SELECT DNAME, LOC FROM DEPT WHERE DNO IN (SELECT DNO FROM
WORKER WHERE SALARY > 10000);
DNAME LOC
----------- ------------
PRODUCTION GROUND FLOOR
SECURITY 1ST FLOOR
(iii) SELECT W.WNAME, D.MANAGER
FROM WORKER AS W, DEPT AS D
WHERE W.DNO = D.DNO;
WNAME MANAGER
------------- ---------
RAHUL SHARMA R K SINGH
MUKESH VYAS D K JAIN
SURESH S ARORA
ANKUR D K JAIN
(iv) SELECT WNAME FROM WORKER WHERE WNAME LIKE 'R%';
WNAME
-------------
RAHUL SHARMA
35 A table named Products in a database named Inventory stores information about 4
products. The table has the following columns: ProductID (integer, primary key),
ProductName (string), Price (float), and Quantity (integer). Assume the database
username is 'admin' and the password is 'secure123'.
Write a Python code that prompts the user to enter a ProductID and updates the
Quantity of that product by adding 10 to the existing quantity. Handle any potential
errors (e.g., the product ID not existing in the table).
Ans.
import mysql.connector
from mysql.connector import Error
def update_product_quantity(product_id):
try:
connection = mysql.connector.connect(
host="localhost",
database="Inventory",
user="admin",
password="secure123" )
if connection.is_connected():
cursor = connection.cursor()
cursor.execute("SELECT Quantity FROM Products
WHERE ProductID = %s", (product_id,))
result = cursor.fetchone()
if result:
current_quantity = result[0]
new_quantity = current_quantity + 10
update_query = "UPDATE Products SET Quantity = %s
WHERE ProductID = %s"
cursor.execute(update_query, (new_quantity, product_id))
connection.commit()
print(f"updated successfully. New quantity: {new_quantity}")
else:
print("Product not found.")
except Error as e:
print(f"Error: {e}")
finally:
if connection.is_connected():
cursor.close()
connection.close()
Ans.
import pickle
(i) Write a function `add_order()` to input order details from the user (order_id,
customer_name, order_date, total_amount) and store them in "Orders.dat". The
program should allow adding multiple orders until the user chooses to stop.
def add_order():
orders = []
try:
with open("Orders.dat", "rb") as file:
orders = pickle.load(file)
except FileNotFoundError:
pass
while True:
order_id = input("Enter order ID: ")
customer_name = input("Enter customer name: ")
order_date = input("Enter order date (YYYY-MM-DD): ")
total_amount = float(input("Enter total amount: "))