CS Practicals Class Xii Comp. Sci. 083
CS Practicals Class Xii Comp. Sci. 083
com/
CLASS-XII
SUBJECT – COMPUTER SCIENCE (083)
PRACTICAL FILE SOLUTION (SESSION 2020-21)
PRACTICAL
NO. OBJECTIVE & SOLUTION
1. Write a program to check a number whether it is palindrome or not.
num=int(input("Enter a number : "))
n=num
res=0
while num>0:
rem=num%10
SOURCE res=rem+res*10
CODE: num=num//10
if res==n:
print("Number is Palindrome")
else:
print("Number is not Palindrome")
OUTPUT:
2. Write a program to display ASCII code of a character and vice versa.
var=True
while var:
choice=int(input("Press-1 to find the ordinal value of a character \nPress-2 to
find a character of a value\n"))
if choice==1:
ch=input("Enter a character : ")
print(ord(ch))
elif choice==2:
val=int(input("Enter an integer value: "))
SOURCE
CODE: print(chr(val))
else:
print("You entered wrong choice")
OUTPUT:
enter a list of numbers : [10,2,5,8,1]
Sum of list elements is : 26
6. Write a program to print fibonacci series using recursion.
def fibonacci(n):
if n<=1:
SOURCE return n
CODE: else:
return(fibonacci(n-1)+fibonacci(n-2))
num=int(input("How many terms you want to display: "))
for i in range(num):
print(fibonacci(i)," ", end=" ")
OUTPUT:
How many terms you want to display: 8
0 1 1 2 3 5 8 13
7. Write a program for binary search using recursion.
def Binary_Search(sequence, item, LB, UB):
if LB>UB:
return -5 # return any negative value
mid=int((LB+UB)/2)
if item==sequence[mid]:
return mid
elif item<sequence[mid]:
UB=mid-1
SOURCE
CODE: return Binary_Search(sequence, item, LB, UB)
else:
LB=mid+1
return Binary_Search(sequence, item, LB, UB)
#__main__
if y==True:
print("String is Palindrome")
else:
print("String is Not Palindrome")
OUTPUT:
Enter the string : madam
String is Palindrome
Write a program to read a text file line by line and display each word separated
9.
by '#'.
fin=open("D:\\python programs\\Book.txt",'r')
L1=fin.readlines( )
s=' '
for i in range(len(L1)):
SOURCE L=L1[i].split( )
CODE: for j in L:
s=s+j
s=s+'#'
print(s)
fin.close( )
Text in file:
hello how are you?
OUTPUT:
python is case-sensitive language.
print(count)
OUTPUT: 9
11. Write a program to count number of words in a file.
fin=open("D:\\python programs\\Story.txt",'r')
str=fin.read( )
L=str.split()
SOURCE
CODE: count_words=0
for i in L:
count_words=count_words+1
print(count_words)
OUTPUT: 16
Write a program to count the number of times the occurrence of 'is' word in a
12.
text file.
SOURCE fin=open("D:\\python programs\\Book.txt",'r')
CODE: str=fin.read( )
L=str.split( )
count=0
for i in L:
if i=='is':
count=count+1
print(count)
fin.close( )
OUTPUT: 3
Write a program to write those lines which have the character 'p' from one text
13.
file to another text file.
fin=open("E:\\book.txt","r")
fout=open("E:\\story.txt","a")
s=fin.readlines( )
for j in s:
SOURCE
CODE: if 'p' in j:
fout.write(j)
fin.close()
fout.close()
OUTPUT: **Write contents of book.txt and story.txt
Create a binary file with name and roll number of student and display the data
14.
by reading the file.
import pickle
def writedata( ):
list =[ ]
while True:
roll = input("Enter student Roll No:")
sname = input("Enter student Name :")
student = {"roll":roll,"name":sname}
list.append(student)
choice= input("Want to add more record(y/n) :")
if(choice=='n'):
break
SOURCE
CODE:
file = open("student.dat","wb")
pickle.dump(list,file)
file.close( )
def readdata( ):
file = open("student.dat", "rb")
list = pickle.load(file)
print(list)
file.close( )
file.close( )
Enter roll number whose name you want to update in binary file :1202
OUTPUT: Enter new name: Harish
Record Updated
17. Write a program to delete a record from binary file.
import pickle
roll = input('Enter roll number whose record you want to delete:')
file = open("student.dat", "rb+")
list = pickle.load(file)
found = 0
SOURCE
CODE: lst = []
for x in list:
if roll not in x['roll']:
lst.append(x)
else:
found = 1
if found == 1:
file.seek(0)
pickle.dump(lst, file)
print("Record Deleted ")
else:
print('Roll Number does not exist')
file.close()
OUTPUT:
Enter roll number whose record you want to delete:1201
Record Deleted
18. Write a program to perform read and write operation with .csv file.
import csv
def readcsv():
with open('C:\\Users\\ViNi\\Downloads\\data.csv','rt')as f:
data = csv.reader(f) #reader function to generate a reader object
for row in data:
SOURCE
CODE: print(row)
def writecsv( ):
with open('C:\\Users\\ViNi\\Downloads\\data.csv', mode='a', newline='') as
file:
writer = csv.writer(file, delimiter=',', quotechar='"')
#Tri.py
class Triangle:
def __init__(self):
print("Trinagle")
Rectangle
Area of Rectangle is : 200
Square
OUTPUT: Area of square is : 100
Trinagle
Area of Triangle is : 24.0
21. Write a program for linear search.
L=eval(input("Enter the elements: "))
n=len(L)
item=eval(input("Enter the element that you want to search : "))
for i in range(n):
SOURCE
CODE: if L[i]==item:
print("Element found at the position :", i+1)
break
else:
print("Element not Found")
Enter the elements: 23,67,44,99,65,33,78,12
OUTPUT: Enter the element that you want to search : 33
Element found at the position : 6
22. Write a program for bubble sort.
L=eval(input("Enter the elements:"))
n=len(L)
for p in range(0,n-1):
for i in range(0,n-1):
SOURCE
CODE: if L[i]>L[i+1]:
t=L[i]
L[i]=L[i+1]
L[i+1]=t
print("The sorted list is : ", L)
OUTPUT:
Enter the elements:[67,13,89,34,65,8,74,19]
The sorted list is : [8, 13, 19, 34, 65, 67, 74, 89]
23. Write a menu based program to perform the operation on stack in python.
class Stack:
def __init__(self):
self.items = [ ]
def size(self): # Size of the stack i.e. total no. of elements in stack
return len(self.items)
s = Stack( )
print("MENU BASED STACK")
cd=True
while cd:
print(" 1. Push ")
print(" 2. Pop ")
print(" 3. Display ")
print(" 4. Size of Stack ")
print(" 5. Value at Top ")
if choice==1:
val=input("Enter the element: ")
s.push(val)
elif choice==2:
if s.items==[ ]:
print("Stack is empty")
else:
print("Deleted element is :", s.pop( ))
elif choice==3:
print(s.items)
elif choice==4:
print("Size of the stack is :", s.size( ))
elif choice==5:
print("Value of top element is :", s.peek( ))
else:
print("You enetered wrong choice ")
def size(Q): # Size of the queue i.e. total no. of elements in queue
return len(Q.items)
q = Queue( )
print("MENU BASED QUEUE")
cd=True
while cd:
print(" 1. ENQUEUE ")
print(" 2. DEQUEUE ")
print(" 3. Display ")
print(" 4. Size of Queue ")
print(" 5. Value at rear ")
if choice==1:
val=input("Enter the element: ")
q.Enqueue(val)
elif choice==2:
if q.items==[ ]:
print("Queue is empty")
else:
print("Deleted element is :", q.Dequeue( ))
elif choice==3:
print(q.items)
elif choice==4:
print("Size of the queue is :", q.size( ))
elif choice==5:
print("Value of rear element is :", q.peek( ))
else:
print("You enetered wrong choice ")
for word in L:
word = word.replace(".","")
word = word.replace(",","")
word = word.replace(":","")
word = word.replace("\"","")
word = word.replace("!","")
word = word.replace("&","")
word = word.replace("*","")
for k in L:
key=k
if key not in d:
count=L.count(key)
d[key]=count
word_counter = collections.Counter(d)
fin.close()
OUTPUT:
the : 505
a : 297
is : 247
in : 231
to : 214
Find the name and salary of those employees whose salary is between 35000
B.
and 40000.
SELECT Ename, salary
SOLUTION
FROM EMPLOYEE
WHERE salary BETWEEN 35000 and 40000;
C. Find the name of those employees who live in guwahati, surat or jaipur city.
SELECT Ename, city
SOLUTION FROM EMPLOYEE
WHERE city IN(‘Guwahati’,’Surat’,’Jaipur’);
D. Display the name of those employees whose name starts with ‘M’.
SELECT Ename
SOLUTION
FROM EMPLOYEE
WHERE Ename LIKE ‘M%’;
Find maximum salary of each department and display the name of that
H. department which has maximum salary more than 39000.
SELECT Dept, max(salary)
SOLUTION
FROM EMPLOYEE
group by Dept
HAVING max(salary)>39000;
32. Queries for Aggregate functions- SUM( ), AVG( ), MIN( ), MAX( ), COUNT( )
a. Find the average salary of the employees in employee table.
Solution:- SELECT avg(salary)
FROM EMPLOYEE;
b. Find the minimum salary of a female employee in EMPLOYEE table.
Solution:- SELECT Ename, min(salary)
FROM EMPLOYEE
WHERE sex=’F’;
c. Find the maximum salary of a male employee in EMPLOYEE table.
Solution:- SELECT Ename, max(salary)
FROM EMPLOYEE
WHERE sex=’M’;
d. Find the total salary of those employees who work in Guwahati city.
Solution:- SELECT sum(salary)
FROM EMPLOYEE
WHERE city=’Guwahati’;
e. Find the number of tuples in the EMPLOYEE relation.
Solution:- SELECT count(*)
FROM EMPLOYEE;
33. Write a program to connect Python with MySQL using database connectivity and
perform the following operations on data in database: Fetch, Update and delete
the data.
A. CREATE A TABLE
import mysql.connector
demodb = mysql.connector.connect(host="localhost", user="root",
passwd="computer", database="EDUCATION")
SOLUTION democursor=demodb.cursor( )
democursor.execute("CREATE TABLE STUDENT (admn_no int primary key,
sname varchar(30), gender char(1), DOB date, stream varchar(15), marks
float(4,2))")