Computer Science Practical File
Computer Science Practical File
Computer Science
Practical File
Name:-Aditya Singh
Class:-XII-C
Roll number:- 04
Link :-
https://drive.google.com/drive/folders/1a3mfAUormaRatpPkl1Qh9mKOfQEL9
ux8?usp=drive_link
for i in range(len(cards)):
shape,value=cards[i]
if shape in ['Diamonds', 'Clubs']:
Dragons+= 1
elif shape == 'Hearts':
if value.isdigit() or value=='Ace':
Wizards+= 1
else:
Dragons+= 1
else:
Wizards += 1
print('Wizards score:',Wizards)
print('Dragons score:',Dragons)
if Wizards==Dragons:
print('Tie!')
elif Wizards>Dragons:
print('Wizards win!')
else:
print('Dragons win!')
playgame()
2) Write a Python program that requests five integer values from the user. It
then prints the maximum and minimum values entered. If the user enters the
values 3, 2, 5, 0, and 1, the program would indicate that 5 is the maximum
and 0 is the minimum. Your program should handle ties properly; for
example, if the user enters 2, 4, 2, 3, and 3, the program should report 2 as
the minimum and 4 as maximum.
Code:-
integers=[]
for i in range(5):
num=int(input('Enter an integer: '))
integers.append(num)
largest= max(integers)
smallest= min(integers)
print("Maximum value:", largest)
print("Minimum value:", smallest)
3) Write a program that simulates a traffic light. The program should consist
of the following:-
● A user defined function trafficLight() that accepts input from the user and
displays an error message if user enters anything other than RED, YELLOW
or GREEN. Function LIGHT() is called and following is displayed
depending upon return value from LIGHT()
o “STOP, your life is precious” if the value returned by LIGHT() is 0.
o “Please WAIT, untill the light is green”, if the value returned by
LIGHT() is 1
o “GO! Thankyou for being patient”, if the value returned by LIGHT() is
2.
● A user defined function LIGHT() that accepts a string as input and returns
0 when the input is RED, 1 when the input is YELLOW and 2 when the
input is GREEN. The input should be passed as an argument. Display
“SPEED THRILLS BUT KILLS” after the function trafficLight() is
executed
Code:-
def trafficLight():
signal = input("Enter the colour of the traffic light: \t")
if (signal not in ("RED","YELLOW","GREEN")):
print("Please enter a valid Traffic Light colour in CAPITALS")
else:
value = light(signal)
if (value == 0):
print("STOP, Your Life is Precious.")
elif (value == 1):
print ("PLEASE GO SLOW.")
else:
print("GO!,Thank you for being patient.")
def light(colour):
if (colour == "RED"):
return(0);
elif (colour == "YELLOW"):
return (1)
else:
return(2)
trafficLight()
print("SPEED THRILLS BUT KILLS")
val = [1000, 900, 500, 400, 100, 90, 50, 40,10, 9, 5, 4,1]
syb = ["M", "CM", "D", "CD","C", "XC", "L", "XL","X", "IX", "V",
"IV","I"]
roman_num = ""
i=0
while num > 0:
for _ in range(num // val[i]):
roman_num += syb[i]
num -= val[i]
i += 1
return roman_num
number = 1987
roman_numeral = int_to_roman(number)
print("Roman numeral of", number, "is:", roman_numeral)
# DC
print(rotate_word("cheer", 7))
print(rotate_word("melon", -10))
7) This question is based on a Puzzler that was broadcast on the radio program
Car Talk. Give me a word with three consecutive double letters. I’ll give you a
couple of words that almost qualify, but don’t. For example, the word
committee, c-o-m-m-i-t-te-e. It would be great except for the ‘i’ that sneaks in
there. Or Mississippi: M-i-s-s-is-s-ip- p-i. If you could take out those i’s it
would work. But there is a word that has three consecutive pairs of letters and to
the best of my knowledge this may be the only word. Of course there are
probably 500 more but I can only think of one. What is the word? Write a
program to find it/them out of the given string
Code:-
def has_three_consecutive_double_letters(word):
count = 0
i=0
while i < len(word) - 1:
if word[i] == word[i + 1]:
count += 1
i += 2
if count == 3:
return True
else:
count = 0
i += 1
return False
def find_words_with_consecutive_double_letters(words):
result = []
for word in words:
if has_three_consecutive_double_letters(word):
result.append(word)
return result
result = find_words_with_consecutive_double_letters(words)
print("Words with three consecutive double letters:", result)
8) Two words are anagrams if you can rearrange the letters from one to spell the
other. Write a function called is_anagram that takes two strings and returns True
if they are anagrams.
Code:-
def is_anagram(str1, str2):
clean_str1 = ''.join(sorted(str1.lower()))
clean_str2 = ''.join(sorted(str2.lower()))
return clean_str1 == clean_str2
print(is_anagram("listen", "silent"))
print(is_anagram("hello", "world"))
9) Complete the following function that determines if the number of even and
odd values in an integer list is the same. The function would return true if the
list contains 5, 1, 0, 2 (two evens and two odds), but it would return false for the
list containing 5, 1, 0, 2, 11 (too many odds). The function should return true if
the list is empty, since an empty list contains the same number of evens and
odds (0 for both). The function does not affect the contents of the list
Code:-
def balanced(a):
count_o=0
count_e=0
for i in a:
if i%2==0:
count_e+=1
else:
count_o+=1
if count_e==count_o:
print('True')
else:
print('False')
#DC
a=[5,1,0,2]
balanced(a)
a=[5,1,2,3,4,5]
balanced(a)
a=[]
balanced(a)
10) Write a program that takes a list of words and creates a dictionary with
frequency (number of occurrences) of word as key and list of words for that
frequency as value. For example, if list is given as [‘the’,’of’, ‘an’, ‘is’, ‘an’,
‘the’] Then dictionary should be {2:[‘the’,’an’],1:[‘of’,’is’]}
Code:-
from collections import defaultdict
def create_frequency_dict(words):
word_count = defaultdict(int)
for word in words:
word_count[word] += 1
frequency_dict = defaultdict(list)
for word, count in word_count.items():
frequency_dict[count].append(word)
return dict(frequency_dict)
frequency_dict = create_frequency_dict(words)
print(frequency_dict)
11) Write a program to find the frequency of values in the given dictionary. For
example, if the dictionary is given as
D={‘P1’:60,’P2’:30,’P3’:50,’P4’:60,’P5’:30,’P6’:10} Then output should be
{10:1,30:2,50:1,60:2}
Code:-
def valuefrequency(D):
frequency=dict()
for value in sorted(D.values()):
if value not in frequency:
frequency[value]=list(D.values()).count(value)
print(frequency)
#Driver Code
D={'P1':60,'P2':30,'P3':50,'P4':60,'P5':30,'P6':10}
valuefrequency(D)
SQL Questions
12)
1. Create the tables and insert tuples in them.
2. Display the details of all the employees.
4. Display the records of all the employees along with their annual salaries. The
Salary column of the table contains monthly salaries of the employees.
6. Display the details of all the employees who are below 30 years of age.
10. Display the details of all the employees whose Grade is not NULL.
11. Display the names of various zones from the table Employee. A zone name
should appear only once
12. Display the various department numbers from the table Employee. A
department number should be displayed only once
13. Display the details of all the employees of department 10 who are above 30
years of age.
14. Display the details of all the employees who are getting a salary of more
than 35000 in the department 30.
15. Display the names and salaries of all the employees who are working neither
in West zone nor in Centre zone.
16. Display the names of all the employees who are working in department 20
or 30.
17. Display the details of all the employees whose salary is between 32000 and
38000
18. Display the details of all the employees whose grade is between ‘A’ and ‘C’
19. Display the names of all the employees who are working in department 20
or 30
20. Display the names and salaries of all the employees who are working
neither in West zone nor in Centre zone.
21. Display the details of all the employees whose salary is between 32000 and
38000.
22. Display the details of all the employees whose grade is between ‘A’ and ‘C’
23. Display the name, salary, and age of all the employees whose names start
with ‘M’.
24. Display the name, salary, and age of all the employees whose names end
with ‘a’.
25. Display the name, salary, and age of all the employees whose names
contain ‘a’
26. Display the name, salary, and age of all the employees whose names do not
contain ‘a’
27. Display the details of all the employees whose names contain ‘a’ as the
second character
28. Display the sum and average of the salaries of all the employees.
29. Display the highest and the lowest salaries being paid in department 10.
31. Display the details of all the employees in the ascending order of their
salaries.
32. Display the details of all the employees in the descending order of their
names.
33. Display the details of all the employees in the ascending order of their
grades and within grades in the descending order of their salaries.
35. Display the highest salary, lowest salary, and average salary of each zone.
36. Display the average age of employees in each department only for those
departments in which average age is more than 30.
37. Put the grade B for all those whose grade is NULL.
38. Increase the salary of all the employees above 30 years of age by 10%.
39. Delete the records of all the employees whose grade is C and salary is
below 30000.
40. Delete the records of all the employees of department 10 who are above 40
years of age.
41. Add another column HireDate of type Date in the Employee table.
ii) To list the item name in descending order of date of purchase where quantity
is more than three
iii) To count number of Items (total quantity) whose cost is more than 10000
iv) To insert a new record in the table STOCK with the following data:
vi) To generate a report on each item code with the item name and total value
(quantity * price)
vii) To find the average cost of all items with more than 2 items:
viii) To find the average cost of items where the date of purchase is before 1-
Jan-2005
14) Create the table and write the SQL queries and capture the screens of
executed queries:
i) To show all information about the Sofas from the INTERIORS table
ii)To list the item names that are priced more than 10000 from the INTERIORS
table
iii) To display item names and dates of stock of those items in which the
discount percentage is more than 15:
iv) To list item names and types of items, where the date of stock is before
'2002-01-22', in descending order of item name
vi) To insert a new row in the INTERIORS table with the following data
viii) To find the average discount from INTERIORS for each type of interiors
ix) To calculate the sum of price from INTERIORS where the date of stock is
before '2002-02-12'
x) To increase the price of all Office tables by 3000 in the INTERIORS table
def display_content_uppercase():
with open('abcd.txt', 'r') as file:
content = file.read()
print(content.upper()) # Display content in uppercase
def count_uppercase_characters():
with open('abcd.txt', 'r') as file:
content = file.read()
count = sum(1 for char in content if char.isupper())
print(f"Total uppercase characters: {count}")
def count_vowels():
vowels = 'aeiouAEIOU'
with open('abcd.txt', 'r') as file:
content = file.read()
count = sum(1 for char in content if char in vowels)
print(f"Total vowels: {count}")
def main():
while True:
print("\nMenu:")
print("1. Display last three characters of all lines")
print("2. Display content in uppercase")
print("3. Count uppercase characters")
print("4. Count vowels")
print("5. Exit")
if choice == '1':
display_last_three_characters()
elif choice == '2':
display_content_uppercase()
elif choice == '3':
count_uppercase_characters()
elif choice == '4':
count_vowels()
elif choice == '5':
print("Exiting the program.")
break
else:
print("Invalid choice. Please try again.")
if __name__ == "__main__":
main()
16)
Develop a complete menu driven application using python mySQL connectivity
based on following parameters. Create functions wherever required. Capture
screenshots of reflected outputs along with code.
i) Database name:STORE
ii) Table names: PRODUCT and CLIENT (as shown above)
iii) Primary keys: pid, cid
iv) Write suitable code in python to create database, tables and to insert the
records.
v) Create a function to display the client name and the product purchased by
the client in descending order of client names
vi) Create a function to increase the price of all the products by 5%. Now
display all the records of product table.
vii) Create a function to remove the records of clients who are from Bangalore.
Now display all the records of Client table.
viii) Create a function to display number of clients from each city.
ix) Create a function to increase the width of column city to 50.
Code:-
i) def createdb():
cur.execute('show databases')
db=cur.fetchall()
if ('store',) not in db:
query='create database STORE'
cur.execute(query)
cur.execute('commit')
print('Database STORE created.')
else:
print('Database already exists.')
cur.execute('use STORE')
ii, iii)
def createtbs():
cur.execute('use STORE')
cur.execute('show tables')
tb=cur.fetchall()
if ('product',) not in tb:
query='create table PRODUCT(\
P_ID varchar(4) primary key,\
PRODUCTNAME varchar(20),\
MANUFACTURER varchar(3),\
PRICE int)'
print('PRODUCT table created.')
cur.execute(query)
cur.execute('commit')
else:
print('PRODUCT table already exists.')
if ('client',) not in tb:
query='create table CLIENT(\
C_ID int primary key,\
CLIENTNAME varchar(20),\
City varchar(20),\
P_ID varchar(4))'
print('CLIENT table created.')
cur.execute(query)
cur.execute('commit')
else:
print('CLIENT table already exists.')
for j in i:
if j=='SHAMPOO':
print(j,end='\t\t')
else:
print(j,end='\t')
print()
print()
viii)def discity():
cur.execute('use STORE')
query='SELECT City,count(*) from CLIENT group by City'
cur.execute(query)
data=cur.fetchall()
for i in data:
for j in i:
print(j,end='\t')
print()
ix)def width():
cur.execute('use STORE')
query='ALTER TABLE CLIENT MODIFY COLUMN City varchar(50)'
cur.execute(query)
cur.execute('commit')
print('Width of City has been extended to 50')
if con.is_connected():
cur=con.cursor()
while True:
choice=int(input('Enter : \n1) To create database \'STORE\' \
\n2) To create tables \'PRODUCT\' and \'CLIENT\' \
\n3) To insert entries in the tables\
\n4) To display client name and product purchased by them\
\n5) To increase price of all products by 5%\
\n6) To remove records of clients from Bangalore\
\n7) To display number of clients from each city\
\n8) To increase the width of column city to 50\
\n0) To exit the program\n'))
if choice==1:
createdb()
elif choice==2:
createtbs()
elif choice==3:
insert()
elif choice==4:
display()
elif choice==5:
increase()
elif choice==6:
rembgl()
elif choice==7:
discity()
elif choice==8:
width()
elif choice==0:
print('Program terminated.')
break
else:
print('Choose valid option')
continue
Code:-
import pickle
def enter_data():
f=open('PRODUCT.DAT','ab')
d={}
vsl1=input('enter product code')
vsl2=input('enter product desc')
vsl3=input('stock')
d['prod_code']=vsl1
d['prod_desc']=vsl2
d['stock']=vsl3
pickle.dump(d,f)
f.close()
print('record inserted')
def display_rec():
f=open('PRODUCT.DAT','rb')
while True:
try:
obj=pickle.load(f)
print(obj)
except EOFError:
f.close()
break
def update():
f=open('PRODUCT.DAT','rb')
l=[]
while True:
try:
obj=pickle.load(f)
l.append(obj)
except EOFError:
f.close()
break
f=open('PRODUCT.DAT','wb')
prod_code=input('Enter the product whose stock is to be modified')
stock=input('enter the new stock')
for i in l:
if i['prod_code']==prod_code:
i['stock']=stock
for rec in l:
pickle.dump(rec,f)
while True:
n=int(input('What do u wanna do: \n1)Enter Data \n2)Display \n3)Update \
n'))
if n==1:
enter_data()
i=input('do u want to continue y/n')
if i.upper()=='Y':
continue
else:
break
elif n==2:
display_rec()
i=input('do u want to continue y/n')
if i.upper()=='Y':
continue
else:
break
elif n==3:
update()
i=input('do u want to continue y/n')
if i.upper()=='Y':
continue
else:
break
else:
print('Choose from 1,2 and 3')
break
import pickle
def enter_records(filename):
records = []
while True:
admno = input("Enter Admission Number (or 'exit' to stop): ")
if admno.lower() == 'exit':
break
name = input("Enter Name: ")
percentage = float(input("Enter Percentage: "))
def display_all_records(filename):
try:
with open(filename, 'rb') as file:
while True:
try:
records = pickle.load(file)
for admno, name, percentage in records:
print(f"Admission Number: {admno}, Name: {name},
Percentage: {percentage}")
except EOFError:
break
except FileNotFoundError
print("No records found.")
def display_above_75(filename):
try:
with open(filename, 'rb') as file:
found = False
while True:
try:
records = pickle.load(file)
for admno, name, percentage in records:
if percentage > 75:
found = True
print(f"Admission Number: {admno}, Name: {name},
Percentage: {percentage}")
except EOFError:
break
if not found:
print("No students with percentage above 75.")
except FileNotFoundError:
print("No records found.")
def menu():
filename = "STUQ2.DAT"
while True:
print("\nMenu:")
print("1. Enter Records")
print("2. Display All Records")
print("3. Display Students with Percentage > 75")
print("4. Exit")
choice = input("Enter your choice: ")
if choice == '1':
enter_records(filename)
elif choice == '2':
display_all_records(filename)
elif choice == '3':
display_above_75(filename)
if __name__ == "__main__":
menu()
Code:-
import pickle
def enter_records(filename):
records = []
while True:
vehicle_type = input("Enter Vehicle Type (or 'exit' to stop): ")
if vehicle_type.lower() == 'exit':
break
no_of_wheels = int(input("Enter Number of Wheels: "))
def display_all_records(filename):
try:
with open(filename, 'rb') as file:
while True:
try:
records = pickle.load(file)
for vehicle in records:
print(f"Vehicle Type: {vehicle[0]}, Number of Wheels:
{vehicle[1]}")
except EOFError:
break
except FileNotFoundError:
print("No records found.")
def count_records(filename):
count = 0
try:
with open(filename, 'rb') as file:
while True:
try:
records = pickle.load(file)
count += len(records)
except EOFError:
break
print(f"Total number of records: {count}")
except FileNotFoundError:
print("No records found.")
def menu():
filename = "vehicles.dat"
while True:
print("\nMenu:")
print("1. Enter Records")
print("2. Display All Records")
print("3. Count Records")
print("4. Exit")
choice = input("Enter your choice: ")
if choice == '1':
enter_records(filename)
elif choice == '2':
display_all_records(filename)
elif choice == '3':
count_records(filename)
elif choice == '4':
print("Exiting the program.")
break
else:
print("Invalid choice. Please try again.")
if __name__ == "__main__":
menu()
20) Create a file PRODUCT.CSV. Sample data of the file is as follows: Write a
menu driven program using functions
● to add sample data to the file
● to display all the records
● to copy/transfer only those records from the file PRODUCT.CSV to another
file “PRO1.CSV” whose quantity is more than 150. Also include the first row
with headings.
● To display the total cost of all the products of the file PRODUCT.CSV
● To search and display the record of that product from the file product.csv
which has maximum cost.
Code:-
import csv
def add_sample_data(filename):
sample_data = [
["PID", "PNAME", "QUANTITY", "COST"],
['P1', "Brush", 200, 50],
['P2', "ToothPaste", 150, 120],
['P3', "Comb", 300, 40],
['P4', "Sheets", 500, 100],
['P5', "Pens", 250, 10]
]
def display_all_records(filename):
try:
with open(filename, 'r') as file:
reader = csv.reader(file)
for row in reader:
print(", ".join(row))
except FileNotFoundError:
print("The file does not exist.")
def total_cost(filename):
total = 0
try:
with open(filename, 'r') as file:
reader = csv.reader(file)
next(reader) # Skip header
for row in reader:
total += float(row[3]) * int(row[2]) # Cost * Quantity
print(f"Total cost of all products: {total:.2f}")
except FileNotFoundError:
print("The file does not exist.")
def product_with_max_cost(filename):
max_cost = 0
max_product = None
try:
with open(filename, 'r') as file:
reader = csv.reader(file)
next(reader) # Skip header
for row in reader:
cost = float(row[3])
if cost > max_cost:
max_cost = cost
max_product = row
if max_product:
def menu():
filename = "PRODUCT.CSV"
while True:
print("\nMenu:")
print("1. Add Sample Data")
print("2. Display All Records")
print("3. Copy Records with Quantity > 150")
print("4. Calculate Total Cost")
print("5. Display Product with Maximum Cost")
print("6. Exit")
choice = input("Enter your choice: ")
if choice == '1':
add_sample_data(filename)
print("Sample data added.")
elif choice == '2':
display_all_records(filename)
elif choice == '3':
copy_records(filename, "PRO1.CSV")
elif choice == '4':
total_cost(filename)
elif choice == '5':
product_with_max_cost(filename)
elif choice == '6':
print("Exiting the program.")
break
else:
print("Invalid choice. Please try again.")
if __name__ == "__main__":
menu()
Code:-
import csv
def add_sample_data(filename):
sample_data = [
["TID", "DESTINATION", "DAYS", "FARE"],
["T10", "Australia", 10, 300],
["T11", "Austria", 15, 750],
["T12", "Rajasthan", 10, 700],
["T13", "France", 12, 650]
]
def display_all_records(filename):
try:
with open(filename, 'r') as file:
reader = csv.reader(file)
for row in reader:
print(", ".join(row))
except FileNotFoundError:
print("The file does not exist.")
def menu():
filename = "Tour.csv"
while True:
print("\nMenu:")
print("1. Add Sample Data")
print("2. Display All Records")
print("3. Display Records with Fare between 500 and 750")
print("4. Exit")
choice = input("Enter your choice: ")
if choice == '1':
add_sample_data(filename)
print("Sample data added.")
elif choice == '2':
display_all_records(filename)
elif choice == '3':
display_fare_between(filename, 500, 750)
elif choice == '4':
print("Exiting the program.")
break
else:
print("Invalid choice. Please try again.")
if __name__ == "__main__":
menu()
Code:-
def MakePush(Package):
n=input('Enter the element to be added')
Package.append(n)
print("elemet pushed on to stack")
def MakePop(Package):
if (Package==[]):
print("Stack Empty-underflow")
else:
print("Deleted element is :",Package.pop())
Package=[]
while True:
i=int(input('Menu\n1)Add an element\n2) Delete the last item \n'))
if i==1:
MakePush(Package)
n=input('want to continue y/n \n')
if n.upper()=='Y':
continue
else:
break
elif i==2:
MakePop(Package)
n=input('want to continue y/n \n')
if n.upper()=='Y':
continue
else:
break
23) Write the functions in Python push (stk, item ) and pop(stk) to check
whether the stack is empty, to add a new item, to delete an item and display the
stack respectively. Implement the menu driven program
Code :-
def Push(stk,item):
stk.append(item)
print("elemet pushed on to stack")
def Pop(stk):
if (stk==[]):
print("Stack Empty-underflow")
else:
print("Deleted element is :",stk.pop())
print(stk)
stk=[]
while True:
i=int(input('Menu\n1)Add an element\n2) Delete the last item \n'))
if i==1:
item=input('enter the integer to be added')
Push(stk,item)
n=input('want to continue y/n \n')
if n.upper()=='Y':
continue
else:
break
elif i==2:
Pop(stk)
n=input('want to continue y/n \n')
if n.upper()=='Y':
continue
else:
break
24) Write a program to perform push operation on a stack to push all prime
numbers from a list entered by a user.
Code:-
def push(l,num):
for i in range(2,num):
if num%i==0:
break
else:
l.append(num)
print(l)
l=[]
while True:
num=int(input('enter the number'))
push(l,num)
n=input('Want to continue y/n ?\n')
if n.upper()=='Y':
continue
else:
print('Bye Have A Good day')
break