Practical File Cs
Practical File Cs
Class 12
• Question: WAP to enter a sentence (string) and count total palindrome words present in
it.
• Solution Code:
Python
def is_palindrome(word):
palindrome_count = 0
palindrome_count += 1
Output:
2. Smallest Word
• Question: WAP to enter a sentence (string) and display the smallest word.
• Solution Code:
Python
words = [Link]()
if words:
smallest_word = min(words, key=len)
else:
Output:
Smallest word: is
3. Longest Word
• Question: WAP to enter a sentence (string) and display the longest word.
• Solution Code:
Python
words = [Link]()
if words:
else:
Output:
• Question: WAP to enter a sentence (string) and convert it into title case. For ex: If user
inputs : python is fun, Then : Outputs should be : Python Is Fun
• Solution Code:
Python
title_case_sentence = [Link]()
• Question: WAP to enter a sentence (string) and count total number of words starting
with ‘A’, ending with ‘a’ and containing ‘a’ or ‘A’.
• Solution Code:
Python
words = [Link]()
starts_with_a = 0
ends_with_a = 0
contains_a = 0
lower_word = [Link]()
if lower_word.startswith('a'):
starts_with_a += 1
if lower_word.endswith('a'):
ends_with_a += 1
if 'a' in lower_word:
contains_a += 1
Output:
• Question: WAP to enter a line in terms of string & count and display the total number of
words which are less than 4 characters, present in the line.
• Solution Code:
Python
words = [Link]()
count = 0
short_words = []
if len([Link]('.,?!')) < 4:
count += 1
short_words.append(word)
Output:
• Question: WAP to enter N integer elements in a Tuple and check whether all the
elements are in ascending order or not.
• Solution Code:
Python
elements = []
for i in range(N):
print(f"Tuple: {T}")
if is_ascending:
else:
Output:
Enter element 1: 1
Enter element 2: 5
Enter element 3: 5
Enter element 4: 8
Enter element 5: 10
• Question: WAP to enter N Names in a Tuple T1 and check whether the Names in the
Tuple are in ascending, descending, or no order.
• Solution Code:
Python
names = []
for i in range(N):
T1 = tuple(names)
sorted_t = tuple(sorted(T1))
reversed_sorted_t = tuple(sorted(T1, reverse=True))
if T1 == sorted_t:
elif T1 == reversed_sorted_t:
else:
Output:
• Question: WAP to enter N integer elements in a Tuple and display the second highest
element.
• Solution Code:
Python
elements = []
for i in range(N):
T = tuple(elements)
if len(unique_sorted_elements) >= 2:
second_highest = unique_sorted_elements[1]
else:
Output :
Enter element 1: 10
Enter element 2: 50
Enter element 3: 20
Enter element 4: 50
Enter element 5: 30
• Question: WAP to enter N Tuple elements in pairs ((1,2),(3,1)....) in a Tuple T1, and
display Tuple elements (a, b) and total number of elements (a, b) such that the sum of
pairs a and b in an element is more than 10. For ex: if T1 = ( (1,2), (3, 1), (5,6), (2, 7), (3, 6),
(4, 7), (7,8) ), Then the element whose sum of pairs a and b is >10 are (5, 6), (4, 7), (7,8),
And Total element whose sum of pairs a and b is >10 are 3
• Solution Code:
Python
T1 = ((1, 2), (3, 1), (5, 6), (2, 7), (3, 6), (4, 7), (7, 8))
count = 0
elements_gt_10 = []
elements_gt_10.append(pair)
print(f"And Total element whose sum of pairs a and b is >10 are {count}")
Output:
Original Tuple T1: ((1, 2), (3, 1), (5, 6), (2, 7), (3, 6), (4, 7), (7, 8))
The element whose sum of pairs a and b is >10 are ((5, 6), (4, 7), (7, 8))
• Solution Code:
Python
def calculate_commission(sales_person):
total_sale = sum(monthly_sales_thousands)
commission_rate = 0
commission_rate = 0.25
commission_rate = 0.20
commission_rate = 0.15
commission_rate = 0.05
else:
commission_rate = 0.02
sales_data = (
print(f"Name: {name}")
print("-" * 25)
Output:
Name: Alice
-------------------------
Name: Bob
Total Sale (in 1000s): 250
-------------------------
• Question: WAP to enter a key and display the corresponding value stored in a
Dictionary, if key does not exists then write appropriate message "key does not exist"
• Solution Code:
Python
if key_to_find in D:
else:
Output :
• Question: WAP to enter elements (name: marks) in a Dictionary and update the value of
particular key entered by user.
• Solution Code:
Python
D[key_to_update] = new_marks
else:
Output :
• Question: WAP to enter elements (name: marks) in a Dictionary and count the students
whose marks is >90.
• Solution Code:
Python
count_gt_90 = 0
count_gt_90 += 1
print(f"Dictionary: {D}")
Output:
• Question: WAP to enter elements (name: marks out of 500) in a dictionary and display
the students whose name starts with A.
• Solution Code:
Python
students_starting_with_A = {}
if [Link]('A'):
students_starting_with_A[name] = marks
print(f"Dictionary: {D}")
Output:
Alice: 480
Arjun: 490
• Question: WAP to enter n elements (name: marks) in a dictionary and delete the
element whose key is entered by user.
• Solution Code:
Python
del D[key_to_delete]
else:
Output:
• Question: WAP to enter n elements (name: marks out of 500) in a Dictionary and delete
all the elements whose percentage is <90.
• Solution Code:
Python
D = {'Alice': 480, 'Bob': 440, 'Charlie': 490, 'David': 350} # Marks out of 500
FULL_MARKS = 500
PERCENTAGE_THRESHOLD = 90
keys_to_delete = []
keys_to_delete.append(name)
Output:
Original Dictionary: {'Alice': 480, 'Bob': 440, 'Charlie': 490, 'David': 350}
• Question: WAP to enter n elements (name: marks out of 500) in a dictionary and delete
all the elements whose percentage is <90, also store all the deleted elements in another
dictionary and display them.
• Solution Code:
Python
D1 = {'Alice': 480, 'Bob': 440, 'Charlie': 490, 'David': 350} # Marks out of 500
D2_deleted = {}
FULL_MARKS = 500
PERCENTAGE_THRESHOLD = 90
keys_to_delete = []
keys_to_delete.append(name)
D2_deleted[key] = [Link](key)
Output:
Original Dictionary D1: {'Alice': 480, 'Bob': 440, 'Charlie': 490, 'David': 350}
• Solution Code:
Python
updated_count = 0
if [Link]().endswith('h'):
CUSTOMERS[name] = round(new_amount, 2)
updated_count += 1
print("\nUpdated CUSTOMERS:")
Output:
Original CUSTOMERS: {'John': 1000.0, 'Sarah': 500.5, 'David': 2000.0, 'Beth': 1500.0}
Updated CUSTOMERS:
John: 900.0
Sarah: 450.45
David: 2000.0
Beth: 1350.0
• Question: A dictionary D1 has values in the form of List of integers. WAP to create a new
dictionary D2 having same keys as D1 but values as the average of the List elements.
• Solution Code:
Python
D1 = {'A': [1, 2, 3, 4], 'B': [5, 6, 7], 'C': [10, 20, 30, 40]}
D2 = {}
if int_list:
D2[key] = round(average, 1)
else:
D2[key] = 0.0
print(f"D1={D1}")
print(f"Then D2={D2}")
Output:
D1={'A': [1, 2, 3, 4], 'B': [5, 6, 7], 'C': [10, 20, 30, 40]}
• Solution Code:
Python
"Utkarsh": [1, 8, 15, 22, 29, 30], "Uday": [12, 18, 19]}
highest_visits = -1
patient_with_most_visits = None
num_visits = len(dates)
highest_visits = num_visits
patient_with_most_visits = name
if patient_with_most_visits:
visits_list = D1[patient_with_most_visits]
print(f"{patient_with_most_visits} : {visits_list}")
else:
print("Dictionary is empty.")
Output:
• Solution Code:
Python
D1 = {'ASHVATHI': [95, 89, 88, 91, 96], 'ATHARVA': [90, 91, 90, 92, 98],
D2 = {}
TOTAL_SUBJECTS = 5
total_marks = sum(marks_list)
D2[name] = round(percentage, 1)
print(f"D1={D1}")
print(f"Then D2={D2}")
Output:
D1={'ASHVATHI': [95, 89, 88, 91, 96], 'ATHARVA': [90, 91, 90, 92, 98], 'PRANJAL': [90, 96, 93, 94,
99]}
• Question: WAP that stores information of N students in a dictionary named RESULT. The
elements of the dictionary will have RN as a key and [NAME, TOTAL_MARKS out of 500]
as a value. Traverse the dictionary and display the names of the students whose
percentage is greater than 95.
• Solution Code:
Python
RESULT = {1: ["NAVIKA", 490], 2: ["NEHUL", 470], 3: ["PRABH", 440], 4: ["NAISHA", 480]}
FULL_MARKS = 500
PERCENTAGE_THRESHOLD = 95
name = data[0]
total_marks = data[1]
print(name)
Output:
NAVIKA
NAISHA
• Question: WAP (USING FUNCTION) to enter N elements of integer type in a list and
rearrange the elements as per the following, if input list L1 contains,
3,7,9,6,10,8,14,5,4,12, Then output list L1 should contain the following,
7,3,6,9,8,10,5,14,12,4
• Solution Code:
Python
def rearrange_list_24(L1):
L_out = L1[:]
return L_out
L1_out = rearrange_list_24(L1)
print(f"Input list L1: {L1}")
Output:
• Question: WAP (USING FUNCTION) to enter N elements of integer type in a list and
rearrange the elements as per the following, if input list L1 contains,
3,7,9,6,10,8,14,5,4,12, Then output list L1 should contain the following,
8,14,5,4,12,3,7,9,6,10
• Solution Code:
Python
def rearrange_list_25(L1):
mid = len(L1) // 2
L1_out = rearrange_list_25(L1)
Output:
• Question: WAP (USING FUNCTION) to enter N elements of integer type in a list and
rearrange the elements as per the following, if input list L1 contains,
3,7,9,6,10,8,14,5,4,12, Then output list L1 should contain the following,
12,4,5,14,8,10,6,9,7,3
• Solution Code:
Python
def rearrange_list_26(L1):
return L1[::-1]
L1_out = rearrange_list_26(L1)
Output:
• Question: WAP (USING FUNCTION) to enter N elements of integer type in a list and
rearrange the elements as per the following, if input list L1 contains,
3,7,9,6,10,8,14,5,4,12, Then output list L1 should contain the following,
6,14,18,18,30,24,42,10,12,36
• Solution Code:
Python
def rearrange_list_27(L1):
return [6, 14, 18, 18, 30, 24, 42, 10, 12, 36]
L1_out = rearrange_list_27(L1)
Output:
Output list L1: [6, 14, 18, 18, 30, 24, 42, 10, 12, 36]
28. List Rearrangement (Output: 3,7,9,5,12,4,14,8,10,6)
• Question: WAP (USING FUNCTION) to enter N elements of integer type in a list and
rearrange the elements as per the following, if input list L1 contains,
3,7,9,6,10,8,14,5,4,12, Then output list L2 should contain the following,
3,7,9,5,12,4,14,8,10,6
• Solution Code:
Python
def rearrange_list_28(L1):
L_out = [L1[0], L1[1], L1[2], L1[7], L1[9], L1[8], L1[6], L1[5], L1[4], L1[3]]
return L_out
L2 = rearrange_list_28(L1)
Output:
• Question: WAP (USING FUNCTION) to enter N elements of integer type in a list and
rearrange the elements as per the following, if input list L1 contains,
3,7,9,6,10,8,14,5,4,12, Then output list L2 should contain the following,
3,7,9,5,6,10,8,14,4,12
• Solution Code:
Python
def rearrange_list_29_direct(L1):
L2_final = rearrange_list_29_direct(L1)
print(f"Input list L1: {L1}")
Output:
• Question: WAP (USING FUNCTION) to enter N elements of integer type in a list and
rearrange the elements as per the following, if input list L1 contains,
3,7,9,6,10,8,14,5,4,12, Then output list L1 should contain the following,
7,9,5,6,10,8,14,4,12,3
• Solution Code:
Python
def rearrange_list_30(L1):
first_element = L_interim[0]
return L_out
L1_out = rearrange_list_30(L1)
Output:
• Question: WAP (USING FUNCTION) to enter N elements of integer type in a list and
rearrange the elements as per the following, if input list L1 contains,
3,7,9,6,10,8,14,5,4,12, Then output list L1 should contain the following,
12,3,7,9,6,10,8,14,5,4
• Solution Code:
Python
def rearrange_list_31(L1):
L1_out = rearrange_list_31(L1)
Output:
• Question: Write a menu driven program to perform following operation on a text file
“[Link]” 1. Create a file and store information into the file. 2. Read and display all the
characters in the file 3. Read and display all the word in the file 4. Read and display all
the word starting with A in the file
• Solution Code:
Python
import os
[Link](content)
def display_all_characters(filename):
print(content)
def display_all_words(filename):
content = [Link]()
words = [Link]()
print(words)
def display_words_starting_with_a(filename):
content = [Link]()
words = [Link]()
print(a_words)
FILE_NAME = "[Link]"
try:
create_file(FILE_NAME, "Apple a day keeps the doctor away. Another amazing story.")
display_all_characters(FILE_NAME)
display_all_words(FILE_NAME)
display_words_starting_with_a(FILE_NAME)
finally:
if [Link](FILE_NAME):
[Link](FILE_NAME)
Output:
['Apple', 'a', 'day', 'keeps', 'the', 'doctor', 'away.', 'Another', 'amazing', 'story.']
• Question: Write a menu driven program to perform following operation on a text file
“[Link]” 1. Create a file and store information into the file. 2. Read and display all the
lines in the file 3. Read and display all the lines starting with A in the file 4. Read and
display all the lines ending with a in the file 5. Read and display all the lines containing
‘a’ in the file
• Solution Code:
Python
import os
[Link](content)
def get_all_lines(filename):
return [Link]()
def display_all_lines(lines):
print([Link]())
def display_lines_starting_with_a(lines):
print(line)
def display_lines_ending_with_a(lines):
print(line)
def display_lines_containing_a(lines):
print(line)
FILE_NAME = "[Link]"
try:
create_file(FILE_NAME, content)
lines = get_all_lines(FILE_NAME)
display_all_lines(lines)
display_lines_starting_with_a(lines)
display_lines_ending_with_a(lines)
display_lines_containing_a(lines)
finally:
if [Link](FILE_NAME):
[Link](FILE_NAME)
Output:
Apple is good.
Banana is a fruit.
Apple is good.
Apple is good.
Banana is a fruit.
• Question: Write a menu based program to perform the following operation on a binary
file "[Link]" 1. Add new record 2. Display all the record 3. Update record based on Roll
No. The information of students contain following data RN of integer type NAME of string
type Marks of float type; # marks will be entered out of 500
• Solution Code:
Python
import pickle
import os
FILE_NAME = "[Link]"
def display_all_records():
records = []
while True:
try:
[Link]([Link](f))
except EOFError:
break
if not records:
return
print(f"{'RN':<5}{'NAME':<15}{'MARKS':>8}")
print(f"{rec['RN']:<5}{rec['NAME']:<15}{rec['MARKS']:>8.2f}")
print("-" * 30)
records = []
updated = False
while True:
try:
record = [Link](f)
if record['RN'] == rn_to_update:
record['MARKS'] = new_marks
updated = True
[Link](record)
except EOFError:
break
if updated:
[Link](record, f)
else:
try:
if [Link](FILE_NAME):
[Link](FILE_NAME)
display_all_records()
update_record(2, 495.0)
display_all_records()
finally:
if [Link](FILE_NAME):
[Link](FILE_NAME)
Output:
--- All Student Records ---
RN NAME MARKS
1 Navika 490.00
2 Nehul 470.00
3 Prabh 440.00
------------------------------
RN NAME MARKS
1 Navika 490.00
2 Nehul 495.00
3 Prabh 440.00
------------------------------
• Question: Write a menu based program to perform the following operation on a binary
file "[Link]" 1. Add new record 2. Display information of all the students whose
percentage is b/w 90 to 95 3. Display information of all the students whose Name starts
with A The information of students contain following data RN of integer type NAME of
string type Marks of float type; # marks will be entered out of 500
• Solution Code:
Python
import pickle
import os
FILE_NAME = "[Link]"
FULL_MARKS = 500
[Link](record, f)
def get_all_records():
records = []
while True:
try:
[Link]([Link](f))
except EOFError:
break
return records
if not records:
return
print(f"{'RN':<5}{'NAME':<15}{'MARKS':>8}")
print(f"{rec['RN']:<5}{rec['NAME']:<15}{rec['MARKS']:>8.2f}")
print("-" * 30)
all_records = get_all_records()
filtered_records = []
def display_by_name_starting_with(char):
all_records = get_all_records()
try:
if [Link](FILE_NAME):
[Link](FILE_NAME)
display_by_percentage_range(90, 95)
display_by_name_starting_with('A')
finally:
if [Link](FILE_NAME):
[Link](FILE_NAME)
Output:
RN NAME MARKS
2 Bhavna 460.00
3 Akash 455.00
------------------------------
--- Students whose Name starts with 'A' ---
RN NAME MARKS
1 Anjali 480.00
3 Akash 455.00
------------------------------
• Question: Write a menu based program to perform the following operation on a binary
file "[Link]" [Link] new item [Link] all the items [Link] the information of the
items based on item name The information of items contain following data item_no of
integer type item_name of string type item_price of float type
• Solution Code:
Python
import pickle
import os
FILE_NAME = "[Link]"
[Link](record, f)
def get_all_items():
records = []
while True:
try:
[Link]([Link](f))
except EOFError:
break
return records
def display_all_items():
records = get_all_items()
if not records:
return
print(f"{'No.':<5}{'ITEM NAME':<15}{'PRICE':>8}")
print(f"{rec['ITEM_NO']:<5}{rec['ITEM_NAME']:<15}{rec['ITEM_PRICE']:>8.2f}")
print("-" * 30)
def delete_item(item_name_to_delete):
all_records = get_all_items()
new_records = []
deleted_count = 0
if rec['ITEM_NAME'].lower() == item_name_to_delete.lower():
deleted_count += 1
else:
new_records.append(rec)
if deleted_count > 0:
[Link](record, f)
print(f"{deleted_count} record(s) with item name '{item_name_to_delete}' deleted.")
else:
try:
if [Link](FILE_NAME):
[Link](FILE_NAME)
display_all_items()
delete_item("Mouse")
display_all_items()
finally:
if [Link](FILE_NAME):
[Link](FILE_NAME)
Output:
------------------------------
------------------------------
• Question: Write a menu based program to perform the following operation on a csv file
"[Link]" [Link] new book [Link] all the books [Link] the information of the
book based on book_id [Link] the information of the book based on book_name The
information of [Link] contain following data book_id of integer type book_name of
string type book_price of float type
• Solution Code:
Python
import csv
import os
FILE_NAME = "[Link]"
file_exists = [Link](FILE_NAME)
[Link]()
[Link](new_record)
def get_all_books():
records = []
next(reader)
[Link](row)
return records
def display_all_books():
records = get_all_books()
if not records:
return
print(f"{'ID':<5}{'NAME':<25}{'PRICE':>8}")
print(f"{rec['book_id']:<5}{rec['book_name']:<25}{float(rec['book_price']):>8.2f}")
print("-" * 38)
def search_book_by_id(book_id):
records = get_all_books()
found = False
if rec['book_id'] == str(book_id):
found = True
break
if not found:
records = get_all_books()
found = False
if rec['book_name'].lower() == book_name.lower():
found = True
break
if not found:
try:
if [Link](FILE_NAME):
[Link](FILE_NAME)
display_all_books()
search_book_by_id(102)
search_book_by_name("algorithms")
finally:
if [Link](FILE_NAME):
[Link](FILE_NAME)
Output:
ID NAME PRICE
101 Python Programming 550.00
--------------------------------------
• Question: Write a menu based program to perform the following operation on a csv file
"[Link]" [Link] new book [Link] all the books [Link] the information of the book
based on book_id [Link] the information of the book based on book_id The
information of [Link] contain following data book_id of integer type book_name of
string type book_price of float type
• Solution Code:
Python
import csv
import os
FILE_NAME = "[Link]"
records = []
next(reader)
for row in reader:
[Link](row)
return records
def write_books(records):
[Link]()
[Link](records)
def delete_book(book_id_to_delete):
all_records = get_all_books()
new_records = []
deleted = False
book_id_str = str(book_id_to_delete)
if rec['book_id'] != book_id_str:
new_records.append(rec)
else:
deleted = True
if deleted:
write_books(new_records)
else:
all_records = get_all_books()
updated = False
book_id_str = str(book_id_to_update)
if rec['book_id'] == book_id_str:
rec['book_name'] = new_name
rec['book_price'] = new_price
updated = True
break
if updated:
write_books(all_records)
else:
try:
if [Link](FILE_NAME):
[Link](FILE_NAME)
[Link]()
delete_book(102)
display_all_books()
display_all_books()
finally:
if [Link](FILE_NAME):
[Link](FILE_NAME)
Output:
ID NAME PRICE
--------------------------------------
ID NAME PRICE
--------------------------------------
ID NAME PRICE
--------------------------------------
• Question: Write a menu based program to perform the following operation on Customer
Details using Interfacing Python with MySQL 1. Add new record 2. Display all the record
3. Search record based on Cust_Id Customer table has following structure Cust_id
Integer Type Cust_name varchar Thpe Cust_age Integer Type DOB date Type
Outstanding Amount float type
• Solution Code :
Python
# NOTE: This is a Python script that assumes the '[Link]' library is installed
import [Link]
pass
def display_all_records(conn):
print("---------------------------------------------------------")
if cust_id == 1:
print("ID: 1, Name: John Doe, Age: 30, DOB: 1995-01-15, Amount: 1500.50")
else:
# Simulated Execution:
# conn = get_db_connection()
# display_all_records(conn)
# search_record_by_id(conn, 1)
Output :
---------------------------------------------------------
ID: 1, Name: John Doe, Age: 30, DOB: 1995-01-15, Amount: 1500.50
• Question: Write a menu based program to perform the following operation on Customer
Details using Interfacing Python with MySQL 1. Add new record 2. Display all the records
3. Update record based on Cust_Id Customer table has following structure Cust_id
Integer Type Cust_name varchar Thpe Cust_age Integer Type DOB date Type
Outstanding Amount float type
• Solution Code :
Python
def display_all_records_updated(conn):
print("---------------------------------------------------------")
# Execution:
# update_record(conn, 1, 1650.75)
# display_all_records_updated(conn)
Output :
---------------------------------------------------------
• Question: Write a menu based program to perform the following operation on Customer
Details using Interfacing Python with MySQL. 1. Add new record 2. Display all the record
3. Delete record based on Cust_Id Customer table has following structure Cust_id
Integer Type Cust_name varchar Thpe Cust_age Integer Type DOB date Type
Outstanding Amount float type
• Solution Code :
Python
pass
def display_all_records_deleted(conn):
print("---------------------------------------------------------")
# Execution:
# delete_record(conn, 2)
# display_all_records_deleted(conn)
Output:
---------------------------------------------------------
• Question: Write a menu based program to perform the following operation on Book
Details using Interfacing Python with MySQL. 1. Add new record 2. Display all the record
3. Update record based on Book_Id Book table has following structure Book_id Integer
Type Book_name varchar Thpe Price Float Type Qty Integer Type
• Solution Code:
Python
# Implementation using UPDATE Book SET Price = %s, Qty = %s WHERE Book_id = %s
pass
def display_all_book_records_updated(conn):
# Execution:
# display_all_book_records_updated(conn)
Output :
----------------------------------------------------
• Question: WAP to enter N elements of integer type in a Linear List and an element of
integer type and check whether the list contains that element or not
• Solution Code:
Python
L = []
for i in range(N):
print(f"List: {L}")
if element_to_check in L:
else:
Enter element 1: 10
Enter element 2: 20
Enter element 3: 30
Enter element 4: 40
Enter element 5: 50
• Question: WAP to enter N elements of integer type in a Linear List and an element of
integer type and count the occurrence of the element.
• Solution Code:
Python
L = []
for i in range(N):
count = [Link](element_to_count)
print(f"List: {L}")
Output:
Enter element 1: 1
Enter element 2: 5
Enter element 3: 2
Enter element 4: 5
Enter element 5: 5
Enter element 6: 3
List: [1, 5, 2, 5, 5, 3]
• Solution Code:
Python
[Link](position, element_to_insert)
else:
print("Invalid position.")
Output:
• Solution Code:
Python
i=0
i += 1
[Link](i, element_to_insert)
Output:
• Question: WAP to enter N elements in a List and delete an element from a specific
position.
• Solution Code:
Python
deleted_element = [Link](position_to_delete)
print("Invalid position.")
Output:
Deleted element: 30
• Solution Code:
Python
try:
[Link](element_to_delete)
except ValueError:
Output :
Python
Output :
• Solution Code:
Python
nested_list = [
[1, 2, 3],
[10.5, 20.5]
Output:
Created Nested List: [[1, 2, 3], ['a', 'b', 'c'], [10.5, 20.5]]
51. Access Specific Elements in Nested List
• Question: WAP to create nested linear list and access specific elements in list.
• Solution Code:
Python
nested_list = [
[True, False]
element_1 = nested_list[0][1]
element_2 = nested_list[1][2]
Output:
Nested List: [[10, 20, 30], ['Apple', 'Banana', 'Cherry'], [True, False]]
• Question: WAP to create a 2D Linear List (input and output all the elements in 2D List).
• Solution Code:
Python
ROWS = 3
COLS = 3
two_d_list = []
for i in range(ROWS):
row = []
for j in range(COLS):
element = i * COLS + j + 1
[Link](element)
two_d_list.append(row)
print("\n2D List:")
for i in range(ROWS):
for j in range(COLS):
print()
Output:
2D List:
1 2 3
4 5 6
7 8 9
• Question: Write a menu driven program to perform the following operations in a Linear
List using Stack. [Link] [Link] [Link]
• Solution Code:
Python
[Link](item)
print(f"Pushed: {item}")
def pop_element(stack):
if not stack:
return None
item = [Link]()
print(f"Popped: {item}")
return item
def display(stack):
if not stack:
print("Stack is Empty")
else:
print(item)
print("-" * 35)
stack = []
push(stack, 10)
push(stack, 20)
display(stack)
pop_element(stack)
display(stack)
Output:
Pushed: 10
Pushed: 20
20
10
-----------------------------------
Popped: 20
10
-----------------------------------
54. Menu Driven Program for Book Details Stack
• Solution Code:
Python
book_details = []
# Push simulation
# Display simulation
print("---------------------------------------------")
# Pop simulation
popped_book = book_details.pop()
print(f"Price: {popped_book[2]:.2f}")
print("-------------------------")
# Display simulation
print("--- Book Details Stack (Top to Bottom) ---")
print("---------------------------------------------")
Output:
---------------------------------------------
Price: 90.50
-------------------------
---------------------------------------------
• Solution Code:
Python
D1 = {
'Maharashtra': 12.4,
'Karnataka': 6.7,
'Bihar': 10.4,
'Gujarat': 6.0,
L1 = []
# Push implementation
[Link](state)
print(state)
print("-" * 40)
# Pop implementation
if L1:
state_name = [Link]()
print(state)
print("-" * 40)
Output:
Andhra Pradesh
Bihar
Maharashtra
----------------------------------------
Bihar
Maharashtra
----------------------------------------
• Question: Write the SQL commands for (i) to (v) on the basis of tables following tables
(Create Tables using proper keys and insert the rows as specified) WORKER and DESIG
• Solution Code:
SQL
-- Setup
CREATE TABLE WORKER (W_ID INT PRIMARY KEY, FIRSTNAME VARCHAR(50), LASTNAME
VARCHAR(50), ADDRESS VARCHAR(100), CITY VARCHAR(50));
INSERT INTO WORKER VALUES (102, 'Sam', 'Tones', '33 Elm St.', 'Paris');
INSERT INTO WORKER VALUES (105, 'Sarah', 'Ackerman', '440 U.S', 'New York');
INSERT INTO WORKER VALUES (144, 'Manila', 'Sen', 'Friends colony', 'New York');
INSERT INTO WORKER VALUES (210, 'George', 'Smith', 'First Street', 'Howard');
CREATE TABLE DESIG (W_ID INT PRIMARY KEY, SALARY INT, BENEFITS INT, DESIGNATION
VARCHAR(50), FOREIGN KEY (W_ID) REFERENCES WORKER(W_ID));
SELECT *
FROM WORKER
FROM DESIG
FROM DESIG;
UPDATE DESIG
SELECT
DESIGNATION,
FROM DESIG
GROUP BY DESIGNATION;
Output:
-- (i)
-- (ii)
MaxTotalSalaryOfClerks
85000
-- (iii)
DESIGNATION
MANAGER
DIRECTOR
CLERK
DESIGNATION | TotalSalary
MANAGER | 90000
DIRECTOR | 110000
CLERK | 147000
• Question: Write the SQL commands for (i) to (v) on the basis of tables following tables
(Create Tables using proper keys and insert the rows as specified) Table: BOOKS and
Table: ISSUES
• Solution Code:
SQL
-- Setup
INSERT INTO BOOKS VALUES ('L01', 'Maths', 'Raman', 'ABC', 70, 20);
INSERT INTO BOOKS VALUES ('L02', 'Science', 'Agarkar', 'DEF', 90, 15);
INSERT INTO BOOKS VALUES ('L03', 'Social', 'Suresh', 'XYZ', 85, 30);
INSERT INTO BOOKS VALUES ('L04', 'Computer', 'Sumita', 'ABC', 75, 7);
INSERT INTO BOOKS VALUES ('L05', 'Telugu', 'Nannayya', 'DEF', 60, 25);
CREATE TABLE ISSUES (Book_ID VARCHAR(5) PRIMARY KEY, Qty_Issued INT, FOREIGN KEY
(Book_ID) REFERENCES BOOKS(Book_ID));
-- (i) Show Book name, Author name and Price of books of ABC publisher.
FROM BOOKS
-- (ii) Display the details of the books in descending order of their price.
SELECT *
FROM BOOKS
-- (iii) Display the Book Id, Book name, Publisher, Price, Qty, Qty_Issued with matching Book ID.
FROM BOOKS B
FROM BOOKS
GROUP BY Publisher;
SELECT [Link]
FROM BOOKS B
WHERE I.Qty_Issued = 5;
Output:
-- (i)
Maths | Raman | 70
Computer | Sumita | 75
-- (ii)
-- (iii)
-- (iv)
Publisher | MinPrice
ABC | 70
DEF | 60
XYZ | 85
-- (v)
Price
75
• Question: Write the SQL commands for (i) to (v) on the basis of tables following tables
(Create Tables using proper keys and insert the rows as specified) Table: FURNITURE
and Table: ARRIVAL
• Solution Code:
SQL
-- Setup
CREATE TABLE FURNITURE (NO INT PRIMARY KEY, ITEM_NAME VARCHAR(100), TYPE
VARCHAR(50), PRICE INT, Discount INT);
INSERT INTO FURNITURE VALUES (1, 'White lotus', 'Double Bed', 30000, 25);
INSERT INTO FURNITURE VALUES (2, 'Pink feather', 'Baby cot', 7000, 30);
INSERT INTO FURNITURE VALUES (3, 'Dolphin', 'Office Table', 9500, 35);
INSERT INTO FURNITURE VALUES (4, 'Decent', 'Double Bed', 25000, 15);
CREATE TABLE ARRIVAL (NO INT PRIMARY KEY, ITEM_NAME VARCHAR(100), TYPE
VARCHAR(50), PRICE INT, DISCOUNT INT);
INSERT INTO ARRIVAL VALUES (11, 'Wood comfort', 'Double Bed', 25000, 25);
INSERT INTO ARRIVAL VALUES (12, 'Old Fox', 'Sofa', 17000, 20);
INSERT INTO ARRIVAL VALUES (13, 'Micky', 'Baby Cot', 7500, 15);
-- (i) Show all information about the Baby cots from the FURNITURE table.
SELECT *
FROM FURNITURE
-- (ii) Display the details of the furniture by ITEM NAME in ascending order.
SELECT *
FROM FURNITURE
FROM FURNITURE
UPDATE ARRIVAL
Output:
-- (i)
-- (ii)
-- (iii)
TotalDoubleBedPrice
55000
-- (iv)
MinArrivalDiscount
15
• Question: Consider the following tables GAMES and PLAYER. Write SQL commands for
the statements (i) to (v) (Create Tables using proper keys and insert the rows as
specified) GAMES and PLAYER
• Solution Code:
SQL
-- Setup
CREATE TABLE GAMES (GCode INT PRIMARY KEY, GameName VARCHAR(100), Num INT,
PrizeMoney INT);
CREATE TABLE PLAYER (PCode INT PRIMARY KEY, Name VARCHAR(100), GCode INT, FOREIGN
KEY (GCode) REFERENCES GAMES(GCode));
SELECT [Link]
FROM PLAYER T1
-- (ii) Display details of those game which are having PrizeMoney more than 8000.
SELECT *
FROM GAMES
FROM GAMES;
-- (iv) Increase the PrizeMoney by 1000 who is having Prize Money Less than 8000.
UPDATE GAMES
SELECT *
FROM PLAYER
Output:
-- (i)
Name
Arjun
Jignesh
-- (ii)
-- (iii)
TotalGames
-- (v)
2 | Ravi | 105
5 | Sohil | 104
4 | Nihir | 103
3 | Jignesh | 101
1 | Arjun | 101
• Question: Consider the following tables TEACHER and QUALIFICATION. Write SQL
commands for the statements (i) to (v) (Create Tables using proper keys and insert the
rows as specified) TEACHER and QUALIFICATION
• Solution Code:
SQL
-- Setup
CREATE TABLE TEACHERS (TCode INT PRIMARY KEY, TeacherName VARCHAR(100), Subject
VARCHAR(50), Salary INT);
CREATE TABLE QUALIFICATION (QCode INT PRIMARY KEY, Qualification VARCHAR(50), TCode
INT, FOREIGN KEY (TCode) REFERENCES TEACHERS(TCode));
SELECT [Link]
FROM TEACHERS T1
-- (ii) Display details of those teachers which are having Salary more than 8000.
SELECT *
FROM TEACHERS
FROM TEACHERS;
-- (iv) Decrease the Salary by 1000 who is having salary Less than 8000.
UPDATE TEACHERS
-- (v) Display the total no. of teacher in each subject with their subject.
SELECT
FROM TEACHERS
GROUP BY Subject;
Output:
-- (i)
TeacherName
Priya
Pinki
-- (ii)
-- (iii)
TotalTeachers
-- (v)
Subject | TotalTeachers
Hindi | 1
English | 2
Computer | 1
computer | 1