CS Practical file PDF
CS Practical file PDF
PRACTICAL FILE
def is_perfect(num):
"""Checks if a number is perfect."""
sum_of_factors = 1 # Include 1 as a factor
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
sum_of_factors += i + num // i # Add both divisor and its complement
return sum_of_factors == num
def is_palindrome(num):
"""Checks if a number is a palindrome."""
return str(num) == str(num)[::-1]
def main():
"""Main function to handle user input and menu choices."""
while True:
try:
n1 = int(input("Enter the first integer (n1): "))
n2 = int(input("Enter the second integer (n2): "))
break
except ValueError:
print("Invalid input. Please enter integers only.")
while True:
print("\nMenu:")
print("a. Count prime numbers")
print("b. Count perfect numbers")
print("c. Count palindromes")
print("d. Exit")
if choice == 'a':
count = count_primes(n1, n2)
print("Number of prime numbers:", count)
elif choice == 'b':
count = count_perfect_numbers(n1, n2)
print("Number of perfect numbers:", count)
elif choice == 'c':
count = count_palindromes(n1, n2)
print("Number of palindromes:", count)
elif choice == 'd':
break
else:
print("Invalid choice. Please try again.")
OUTPUT:
sum = 0
for i in range(1, n + 1):
term = factorial(2 * i + 1) / (x**i) # Calculate each term
sign = (-1)**i # Alternate the sign
sum += sign * term
return sum
def main():
"""Prompts the user for input and calls the sum_series function."""
try:
x = float(input("Enter the value of x: "))
n = int(input("Enter the value of n: "))
sum = sum_series(x, n)
print("Sum of the series:", sum)
except ValueError as e:
print("Invalid input. Please enter a numeric value for x and a non-negative
integer for n.")
print(e)
OUTPUT :
def interchange_halves(list1):
"""Interchanges the first half and second half of a list."""
mid = len(list1) // 2
list1[:mid], list1[mid:] = list1[mid:], list1[:mid]
def reverse_elements(list1):
"""Reverses each element in a list."""
list1 = [str(x)[::-1] for x in list1] # Convert numbers to strings for reversing
def main():
"""Main function to handle user input and menu choices."""
while True:
try:
list1 = list(map(int, input("Enter a list of numeric data (separated by spaces):
").split()))
break
except ValueError:
print("Invalid input. Please enter only numeric values.")
while True:
print("\nMenu:")
print("a. Find largest and smallest elements")
print("b. Interchange halves of the list")
print("c. Reverse each element of the list")
print("d. Exit")
if choice == 'a':
largest, smallest = find_largest_smallest(list1.copy()) # Use a copy to avoid
modifying the original list
print("Largest element:", largest)
print("Smallest element:", smallest)
elif choice == 'b':
interchange_halves(list1)
print("List after interchanging halves:", list1)
elif choice == 'c':
reverse_elements(list1)
print("List after reversing elements:", list1)
elif choice == 'd':
break
else:
print("Invalid choice. Please try again.")
OUTPUT:
else:
# Handle other types or unsupported types
print(f"Unsupported type: {type(element)}")
OUTPUT:
return result
OUTPUT:
Q-6) Create a dictionary with Book with bookno as key field and
name, price, qty, category and amount as values in form of a
list. The amount to calculated as qty * price.
Write a menu driven program using UDFs to do the
following:
a. A function to search and display details according to
user given book no.
b. A function to count all records with amount >5000
c. A function to count all books with user given category
The above functions should take a dictionary as parameter
CODE: def create_book_dictionary():
"""Creates a dictionary of books with calculated amount."""
books = {}
while True:
bookno = input("Enter book number (or 'done' to finish): ")
if bookno == 'done':
break
name = input("Enter book name: ")
price = float(input("Enter book price: "))
qty = int(input("Enter book quantity: "))
category = input("Enter book category: ")
amount = qty * price
books[bookno] = [name, price, qty, category, amount]
return books
def main():
"""Main function to handle user input and menu choices."""
books = create_book_dictionary()
while True:
print("\nMenu:")
print("a. Search book by number")
print("b. Count records with amount > 5000")
print("c. Count books by category")
print("d. Exit")
if choice == 'a':
bookno = input("Enter book number to search: ")
search_book(books, bookno)
elif choice == 'b':
count = count_records_with_amount_greater_than(books, 5000)
print("Number of records with amount > 5000:", count)
elif choice == 'c':
category = input("Enter category to count books: ")
count = count_books_by_category(books, category)
print("Number of books in category", category + ":", count)
elif choice == 'd':
break
else:
print("Invalid choice. Please try again.")
OUTPUT:
TEXT FILE
MANIPULATION
Q-1) Write a Python program to create a text file “sample.txt” by
taking contents from the user and perform the following
operations:
a. Count the number of digits, alphabets, special characters
and vowels each line. Also display the line number.
b. Count all lines which starting with a vowel.
c. Display all lines whose size is less than n no. characters.
Accept n from user.
d. Count the occurrence of “The/the” in the file.
e. Count all lines begin with the letter “T/t” to another file.
Display the content of the new file.
f. Display the average word size.
Average word size = sum of size of each word / no. of
words the file.
g. Transfer all alternate words to another file.
h. Transfer all lines not starting with a vowel to another file.
CODE: import string
def count_characters(line):
num_digits = sum(1 for char in line if char.isdigit())
num_alphabets = sum(1 for char in line if char.isalpha())
num_special_chars = sum(1 for char in line if char in string.punctuation)
num_vowels = sum(1 for char in line if char.lower() in 'aeiou')
return num_digits, num_alphabets, num_special_chars, num_vowels
def count_lines_starting_with_vowel(file_content):
return sum(1 for line in file_content if line.strip() and line[0].lower() in 'aeiou')
def average_word_size(file_content):
words = [word.strip(string.punctuation) for line in file_content for word in
line.split()]
total_word_size = sum(len(word) for word in words)
total_words = len(words)
return total_word_size / total_words if total_words > 0 else 0
OUTPUT:
OUTPUT:
CSV FILE
MANIPULATION
Q-1) Write a program to create a csv file by accepting
itemno, item name, category, price and quantity from
user till user wants. Also Calculate Amount as price*
quantity. Write a menu driven program to do the
following operations:
a.Display the contents of the file
b.Count number of records for pulses category of item.
c. Search and display the records based on user given item
no.
d.Search and display the records based on user given item
name.
e.Count the number of records for amount >1000.
CODE: while True:
item_no = input("Enter ItemNo (or 'exit' to finish): ")
if item_no.lower() == 'exit':
break
if choice == '1':
display_contents(csv_file_name)
elif choice == '2':
count_pulses_category = count_records_pulses_category(csv_file_name)
print(f"Number of records for 'Pulses' category: {count_pulses_category}")
elif choice == '3':
user_item_no = input("Enter the item no. to search: ")
search_and_display_by_item_no(csv_file_name, user_item_no)
elif choice == '4':
user_item_name = input("Enter the item name to search: ")
search_and_display_by_item_name(csv_file_name, user_item_name)
elif choice == '5':
count_amount_gt_1000 = count_records_amount_gt_1000(csv_file_name)
print(f"Number of records with amount > 1000: {count_amount_gt_1000}")
elif choice == '6':
print("Exiting the program.")
break
else:
print("Invalid choice. Please enter a valid option.")
OUTPUT:
def read_from_csv(file_name):
with open(file_name, 'r') as csv_file:
csv_reader = csv.reader(csv_file)
header = next(csv_reader)
data = [row for row in csv_reader]
return header, data
def display_all_records(file_name):
header, data = read_from_csv(file_name)
print("\nAll Records:")
print(','.join(header))
for row in data:
print(','.join(row))
# Menu-driven program
while True:
print("\nMenu:")
print("a. Display all records")
print("b. Count students with percentage between 85-90")
print("c. Display details of students of a particular stream")
print("d. Display details of students with a particular grade")
print("e. Copy students with percentage >95 to another file")
print("f. Exit")
if choice == 'a':
display_all_records(csv_file_name)
elif choice == 'b':
count = count_students_percentage_between(csv_file_name, 85, 90)
print(f"Number of students with percentage between 85-90: {count}")
elif choice == 'c':
user_stream = input("Enter the stream to display details: ")
display_students_of_stream(csv_file_name, user_stream)
elif choice == 'd':
user_grade = input("Enter the grade to display details: ")
display_students_with_grade(csv_file_name, user_grade)
elif choice == 'e':
min_percentage = float(input("Enter the minimum percentage to copy records:
"))
output_file_name = "high_percentage_students.csv"
copy_students_to_another_file(csv_file_name, output_file_name,
min_percentage)
elif choice == 'f':
print("Exiting the program.")
break
else:
print("Invalid choice. Please enter a valid option.")
OUTPUT:
BINARY FILE
MANIPULATION
Q-1) Write a menu driven program to create a list by taking
bookno, name, price, quantity, category from user.
a. Create binary file storing the contents of the list.
b. Display all Also calculate Amount which should be
calculated by multiplying price* quantity.
c. Search and display record on Bookno.
d. Search and display record on name.
e. Count all records of a user given category.
f. Delete a records matching the user given record number
g. Edit the nth record. Input n from user
CODE: import pickle
class Book:
def __init__(self, bookno, name, price, quantity, category):
self.bookno = bookno
self.name = name
self.price = price
self.quantity = quantity
self.category = category
def calculate_amount(self):
return self.price * self.quantity
def read_from_binary_file(file_name):
try:
with open(file_name, 'rb') as binary_file:
book_list = pickle.load(binary_file)
return book_list
except FileNotFoundError:
return []
def display_all_books(book_list):
print("\nAll Books:")
for book in book_list:
amount = book.calculate_amount()
print(f"BookNo: {book.bookno}, Name: {book.name}, Price: {book.price},
Quantity: {book.quantity}, Category: {book.category}, Amount: {amount}")
book = book_list[n - 1]
# Main program
book_list = []
while True:
print("\nMenu:")
print("a. Create binary file storing the contents of the list")
print("b. Display all books and calculate Amount")
print("c. Search and display record on BookNo")
print("d. Search and display record on Name")
print("e. Count all records of a user given category")
print("f. Delete a record matching the user given record number")
print("g. Edit the nth record. Input n from the user")
print("h. Exit")
if choice == 'a':
# Taking input from the user to create the list
book_list = []
while True:
bookno = input("Enter BookNo (or 'exit' to finish): ")
if bookno.lower() == 'exit':
break
name = input("Enter Name: ")
price = float(input("Enter Price: "))
quantity = int(input("Enter Quantity: "))
category = input("Enter Category: ")
OUTPUT:
Q-2)
Write
a
program to create a
binary file to store records of a shop having details as itemno,
Name, QOH (OtyOnhand), Price. Create a menu driven program
to:
a. Create above binary file(Where record is represented as
Nested List)
b. Display all records
c. Display all records whose Price is more than 500
d. Transfer all records whose QOH <200 to another file
CODE: import pickle
class ShopItem:
def __init__(self, itemno, name, qoh, price):
self.itemno = itemno
self.name = name
self.qoh = qoh
self.price = price
def create_binary_file(file_name):
item_list = []
while True:
itemno = input("Enter ItemNo (or 'exit' to finish): ")
if itemno.lower() == 'exit':
break
name = input("Enter Name: ")
qoh = int(input("Enter QOH (Quantity On Hand): "))
price = float(input("Enter Price: "))
def display_all_records(file_name):
try:
with open(file_name, 'rb') as binary_file:
item_list = pickle.load(binary_file)
print("\nAll Records:")
for item in item_list:
print(f"ItemNo: {item[0]}, Name: {item[1]}, QOH: {item[2]}, Price:
{item[3]}")
except FileNotFoundError:
print("File not found. Please create the file first.")
# Main program
while True:
print("\nMenu:")
print("a. Create binary file")
print("b. Display all records")
print("c. Display records whose Price is more than 500")
print("d. Transfer records whose QOH < 200 to another file")
print("e. Exit")
if choice == 'a':
file_name = input("Enter the binary file name to create: ")
create_binary_file(file_name)
elif choice == 'b':
file_name = input("Enter the binary file name to display: ")
display_all_records(file_name)
elif choice == 'c':
file_name = input("Enter the binary file name to display records: ")
display_records_above_price(file_name, 500)
elif choice == 'd':
file_name = input("Enter the binary file name to transfer records from: ")
new_file_name = input("Enter the new binary file name to store transferred
records: ")
transfer_records_below_qoh(file_name, 200, new_file_name)
elif choice == 'e':
print("Exiting the program.")
break
else:
print("Invalid choice. Please enter a valid option.")
OUTPUT:
while True:
accno = input("Enter Account Number (or 'exit' to finish): ")
if accno.lower() == 'exit':
break
name = input("Enter Name: ")
type_of_account = input("Enter Type of Account (Saving/Fixed/Recurring):
").capitalize()
balance = float(input("Enter Balance: "))
record = {
"Accno": accno,
"Name": name,
"Type_of_Account": type_of_account,
"Balance": balance
}
account_records.append(record)
def display_and_count_records(file_name):
try:
with open(file_name, 'rb') as binary_file:
account_records = pickle.load(binary_file)
print("\nAll Records:")
count = 0
for record in account_records:
print(record)
count += 1
except FileNotFoundError:
print("File not found. Please create the file first.")
except FileNotFoundError:
print("File not found. Please create the file first.")
except FileNotFoundError:
print("File not found. Please create the file first.")
except FileNotFoundError:
print("File not found. Please create the file first.")
# Main program
file_name = "account.dat"
while True:
print("\nMenu:")
print("a. Create binary file")
print("b. Display and count all records")
print("c. Search and edit record based on Accno")
print("d. Search and display all records based on Name")
print("e. Count all records with balance > 500000")
print("f. Count all records matching with a user given Type of account")
print("g. Exit")
if choice == 'a':
create_binary_file(file_name)
elif choice == 'b':
display_and_count_records(file_name)
elif choice == 'c':
user_accno = input("Enter the Accno to edit: ")
search_and_edit_record(file_name, user_accno)
elif choice == 'd':
user_name = input("Enter the Name to search: ")
search_and_display_by_name(file_name, user_name)
elif choice == 'e':
threshold_balance = float(input("Enter the threshold balance: "))
count_records_above_balance(file_name, threshold_balance)
elif choice == 'f':
user_account_type = input("Enter the Type of Account to count: ")
count_records_by_account_type(file_name, user_account_type)
elif choice == 'g':
print("Exiting the program.")
break
else:
print("Invalid choice. Please enter a valid option.")
OUTPUT:
DATA STRUCTURE-
STACK
Q-1) Write a program to create a stackA with each element as
an integer. Write a menu driven programs to include functions
to:
1. Push() – push the integer element into the stackA
2. Pop() – pop the integer element from the stackA
3. isempty() – check whether the stackA is empty or not
4. dispstack() – display stack contents
5. Transfer all perfect numbers from stackA to stackB and
Display
6. Transfer all palindrome numbers from stackA to stackB and
Display
7. Transfer all prime numbers from stackA to stackB and
Display
CODE: class Stack:
def __init__(self):
self.items = []
def pop(self):
if not self.isempty():
item = self.items.pop()
print(f"{item} popped from the stack.")
return item
else:
print("Stack is empty. Cannot pop from an empty stack.")
return None
def isempty(self):
return len(self.items) == 0
def dispstack(self):
if not self.isempty():
print("Stack contents:")
print(self.items)
else:
print("Stack is empty.")
@staticmethod
def is_perfect(num):
return num > 1 and sum(i for i in range(1, num) if num % i == 0) == num
@staticmethod
def is_palindrome(num):
return str(num) == str(num)[::-1]
@staticmethod
def is_prime(num):
if num < 2:
return False
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
return False
return True
# Main program
stackA = Stack()
stackB = Stack()
while True:
print("\nMenu:")
print("1. Push")
print("2. Pop")
print("3. Check if stackA is empty")
print("4. Display stackA")
print("5. Transfer perfect numbers from stackA to stackB and Display")
print("6. Transfer palindrome numbers from stackA to stackB and Display")
print("7. Transfer prime numbers from stackA to stackB and Display")
print("8. Exit")
if choice == '1':
element = int(input("Enter the integer element to push: "))
stackA.push(element)
elif choice == '2':
stackA.pop()
elif choice == '3':
if stackA.isempty():
print("stackA is empty.")
else:
print("stackA is not empty.")
elif choice == '4':
stackA.dispstack()
elif choice == '5':
stackA.transfer_perfect_numbers(stackB)
print("Perfect numbers transferred from stackA to stackB.")
print("stackA:")
stackA.dispstack()
print("stackB:")
stackB.dispstack()
elif choice == '6':
stackA.transfer_palindrome_numbers(stackB)
print("Palindrome numbers transferred from stackA to stackB.")
print("stackA:")
stackA.dispstack()
print("stackB:")
stackB.dispstack()
elif choice == '7':
stackA.transfer_prime_numbers(stackB)
print("Prime numbers transferred from stackA to stackB.")
print("stackA:")
stackA.dispstack()
print("stackB:")
stackB.dispstack()
elif choice == '8':
print("Exiting the program.")
break
else:
print("Invalid choice. Please enter a
OUTPUT:
Q-2) Write a program to create
a stack, containing student
data, consisting of
Admissionno, Name and
Percentage represented as a
list. Include functions to:
1. Push() – Push the student
record into the stack
2. Pop() – Pop the student
record from the stack
3. isempty() – Check whether
the stack is empty or not
4. dispstack() – Display all
the student records of the
stack
5. dispperc() – Display all
student records scoring a
user given percentage
CODE: class StudentStack:
def __init__(self):
self.stack = []
def pop(self):
if not self.is_empty():
return self.stack.pop()
else:
print("Stack is empty. Cannot pop.")
return None
def is_empty(self):
return len(self.stack) == 0
def display_all(self):
print("All Student Records in the Stack:")
for record in self.stack:
print(f"AdmissionNo: {record['AdmissionNo']}, Name: {record['Name']},
Percentage: {record['Percentage']}")
# Main program
student_stack = StudentStack()
while True:
print("\nMenu:")
print("1. Push student record")
print("2. Pop student record")
print("3. Check if the stack is empty")
print("4. Display all student records in the stack")
print("5. Display student records with a given percentage")
print("6. Exit")
if choice == '1':
admission_no = input("Enter Admission Number: ")
name = input("Enter Name: ")
percentage = float(input("Enter Percentage: "))
student_stack.push(admission_no, name, percentage)
print("Student record pushed into the stack.")
elif choice == '2':
popped_record = student_stack.pop()
if popped_record is not None:
print("Student record popped from the stack:")
print(f"AdmissionNo: {popped_record['AdmissionNo']}, Name:
{popped_record['Name']}, Percentage: {popped_record['Percentage']}")
elif choice == '3':
if student_stack.is_empty():
print("Stack is empty.")
else:
print("Stack is not empty.")
elif choice == '4':
student_stack.display_all()
elif choice == '5':
user_percentage = float(input("Enter the percentage to display matching
records: "))
student_stack.display_by_percentage(user_percentage)
elif choice == '6':
print("Exiting the program.")
break
else:
print("Invalid choice. Please enter a valid option.")
OUTPUT:
COMPUTER SCIENCE
MY SQL COMMANDS
Q-1) Create a Table Empl to store employee details as shown
below and write statements for following queries based on the
table.
empno ename job mgr hiredate sal comm deptno
8369 SMITH CLERK 8902 18-12-1990 800 NULL 20
8499 ANYA SALESMAN 8698 20-02-1991 1600 300 30
8521 SETH SALESMAN 8698 22-02-1991 1250 500 30
8566 MAHADEVAN MANAGER 8839 02-04-1991 2985 NULL 20
8654 MOMIN SALESMAN 8698 28-09-1991 1250 1400 30
8698 BINA MANAGER 8839 01-05-1991 2850 NULL 30
8882 SHIVANSH MANAGER 8839 09-06-1991 2450 NULL 10
8888 SCOTT ANALYST 8566 09-12-1992 3000 NULL 20
8839 AMIR PRESIDENT NULL 18-11-1991 5000 NULL 10
8844 KULDEEP SALESMAN 8698 08-09-1991 1500 0 30
a. Write a query to display EName and Sal of the employees
whose salary are greater than or equal to 2200?
b. Write a query to display details of employs who are not
getting commission?
c. Write a query to display employee name and salary of
those employees who don’t have their salary in range of
2500 to 4000?
d. Write a query to display the name, job title and salary of
employees who don’t have manager and joined after 1990?
e. Write a query to display the name of employee whose
name contains “A” as third alphabet?
f. Write a query to display the name of employee whose
name contains “T” as last alphabet and dept. no is 30?
g. Write a query to display the name of employee whose
name contains “M” as First and “L” as third alphabet?
h. Write a query to display details of employees with the text
“Not given”, if commission is null?
i. Display name and salary of all the employees in the
decreasing order of name.
j. Increase the salary of all employees by 5% who are
Manager and joined before 1991.
k. Delete the records of all employees whose dept. is 20 and
designation is clerk.
l. Display all the records arranged in ascending order of Dept.
no and within it descending order of salary.
m. Display the designations given by the company. The
designation should appear only once.
n. Add another column Status (varchar(10)) in the table.
o. Replace the column Status with permanent for those
employees who have joined before 1991
ANSWER:
a. SELECT EName, Sal FROM Empl WHERE Sal >= 2200;
b. SELECT * FROM Empl WHERE Comm IS NULL;
c. SELECT EName, Sal FROM Empl WHERE Sal NOT BETWEEN 2500 AND 4000;
d. SELECT EName, job, Sal FROM Empl WHERE mgr IS NULL AND hiredate=>31-12-
1990;
e. SELECT Ename FROM Empl WHERE SUBSTR(EName, 3, 1) = 'A';
f. SELECT Ename FROM Empl WHERE SUBSTR(EName, -1) = 'T' AND deptno = 30;
g. SELECT Ename FROM Empl WHERE SUBSTR(EName, 1, 1) = 'M' AND
SUBSTR(EName, 3, 1) = 'L';
h. SELECT *, COALESCE(commission, 'Not given') AS commission FROM employees
WHERE commission IS NULL
i. SELECT EName, Sal FROM Empl ORDER BY EName DESC;
j. UPDATE Empl SET Sal = Sal * 1.05 WHERE job = 'MANAGER' AND hiredate=>1-
1-1991;
k. DELETE FROM Empl WHERE deptno = 20 AND job = 'CLERK';
l. SELECT * FROM Empl ORDER BY deptno ASC, Sal DESC;
m. SELECT DISTINCT job FROM Empl;
n. ALTER TABLE Empl ADD Status VARCHAR(10);
o. UPDATE Empl SET Status = 'Permanent' WHERE hire=>1-1-1991;
Q-4) Write SQL queries from (i) to (iv) and find outputs for SQL
queries (v) to (viii), which are based on the tables
Table: VEHICILE
VCOD
E CEHICLETYPE PERKM
V05 SUV 30
V04 CAR 18
TABLE: TRAVEL
NO
CNO CNAME TRAVELDATE KM VCODE P
20
101 K.Niwal 13-12-2015 0 V01 32
12
103 Fredrick Sym 21-03-2016 0 V03 45
45
105 Hitesh Jain 23-04-2016 0 V02 42
102 Ravi Anish 13-01-2016 80 V02 40
107 John Malina 10-02-2015 65 V04 2
104 Sahanubhuti 28-01-2016 90 V05 4
cursor.execute("INSERT INTO item VALUES (%s, %s, %s, %s)", (item_no, name,
price, item_type))
print("Record inserted successfully.")
if record:
print(record)
else:
print("Record not found.")
# Main function
def main():
connection = mysql.connector.connect(
host="your_host",
user="your_user",
password="your_password",
database="your_database"
)
cursor = connection.cursor()
create_table(cursor)
while True:
print("\nMenu:")
print("1. Create Table")
print("2. Insert New Records")
print("3. Display All Records")
print("4. Search and Display")
print("5. Count and Display")
print("6. Delete Record")
print("7. Edit Record")
print("8. Arrange Records (Ascending)")
print("9. Arrange Records (Descending)")
print("0. Exit")
if choice == '1':
create_table(cursor)
elif choice == '2':
insert_record(cursor)
elif choice == '3':
display_all_records(cursor)
elif choice == '4':
search_and_display(cursor)
elif choice == '5':
count_and_display(cursor)
elif choice == '6':
delete_record(cursor)
elif choice == '7':
edit_record(cursor)
elif choice == '8':
arrange_records(cursor, "ASC")
elif choice == '9':
arrange_records(cursor, "DESC")
elif choice == '0':
print("Exiting the program.")
break
else:
print("Invalid choice. Please enter a valid option.")
cursor.close()
connection.close()