XII CS Term1 Practical Solution
XII CS Term1 Practical Solution
COMPUTER SCIENCE
PRACTICAL RECORD (TERM-
1)
CLASS : XII
2021-2022
Acknowledgement:
I, …………………………….of class XII –
Section ….. would like to express our sincere
gratitude to our
computer science teacher
Ms.APARNA DHIRDE,
PGT (COMPUTER SCIENCE), for her vital
support, guidance and encouragement –
without which
this project would not have come forth.
CERTIFICATE
This is to certify that, Practical on Computer Science
(Term-1) is successfully completed by
….……………………… of
Class: XII, Division: …….
Roll no. :………………..
for the academic year
2021-2022.
Signature:
Examiner (Subject Teacher)
Principal
Date: / / 2022
INDEX
XII CS – Practical Assignments for TERM 1
Assignment 1:
Write a python program to search first occurrence of an element in a list by using Linear search and
display frequency of each element present in list [List and search element should be entered by user]
Ans:
L=[]
c=0
n=int(input('how many items you want to enter in list:'))
for i in range(0,n):
a=int(input('enter item:'))
L.append(a)
print(L)
S=set(L)
S=list(S)
D={}
for i in S:
c=0
for j in L:
if i==j:
c+=1
D[i]=c
for k in D:
print("The frequency of ",k," is ", D[k])
Output is:
how many items you want to enter in list:5
enter item:4
enter item:3
enter item:4
enter item:4
enter item:7
[4, 3, 4, 4, 7]
The frequency of 3 is 1
The frequency of 4 is 3
The frequency of 7 is 1
Enter item to be search:4
Element found at index 0 and position 1
Assignment 2:
Write a python program to sort elements of a list in ascending and descending order
by using bubble sort. Write user defined function.
Ans:
def BSort(Arr, S):
Arr = [ ]
S = int(input("Please Enter the Total Number of Elements : "))
for i in range(S):
value = int(input("Please enter the %d Element of List1 : " %i))
Arr.append(value)
BSort(Arr, S)
print("The Sorted List in Ascending Order : ", Arr)
print("The Sorted List in Descending Order : ", Arr[::-1])
Output is:
Please Enter the Total Number of Elements : 5
Please enter the 0 Element of List1 : 34
Please enter the 1 Element of List1 : -8
Please enter the 2 Element of List1 : 544
Please enter the 3 Element of List1 : 3
Please enter the 4 Element of List1 : 2
The Sorted List in Ascending Order : [-8, 2, 3, 34, 544]
The Sorted List in Descending Order : [544, 34, 3, 2, -8]
Assignment 3:
Write a python program using function to pass list to a function and double the odd
values and half even values of a list and display list element after changing.
Ans:
def splitevenodd(A):
evenlist = []
oddlist = []
for i in A:
if (i % 2 == 0):
evenlist.append(i//2)
else:
oddlist.append(i*i)
print("Even lists:", evenlist)
print("Odd lists:", oddlist)
A=list()
n=int(input("Enter the size of the List ::"))
print("Enter the Elements of List ::")
for i in range(int(n)):
k=int(input(""))
A.append(k)
splitevenodd(A)
Output is:
Enter the size of List ::5
Enter the Elements of List ::
12
3
14
5
1
Even lists: [6, 7]
Odd lists: [9, 25, 1]
Assignment 4:
Write a Python program input n numbers in tuple and count how many even and odd
numbers are entered.
Ans:
l=[]
Output is:
Please Enter the Total Number of Elements : 5
Please enter the 0 Element of List1 : 34
Please enter the 1 Element of List1 : 3
Please enter the 2 Element of List1 : 2
Please enter the 3 Element of List1 : 56
Please enter the 4 Element of List1 : 3
Number of even numbers : 3
Number of odd numbers : 2
Assignment 5:
Write a menu driven program in python to delete name of a student from dictionary and to search
phone no of a student by student name. Create menu as below:
MENU
1. Delete from Dictionary
2. Search Phone number using name from Dictionary
3. Exit
Ans:
phonebook=dict()
while True:
print("******MENU\*******n")
print('1:Delete from Dictionary')
print('2:Search Phone number using name from Dictionary')
print('3:Exit\n')
ch=int(input('Enter your choice:'))
if ch==1:
n=int(input("Enter total number of friends:"))
i=1
while(i<=n):
a=input("enter name :")
b=int(input("enter phone number:"))
phonebook[a]=b
i=i+1
print(phonebook)
print('---------------------------------')
name=input("Enter name to delete:")
del phonebook[name]
k=phonebook.keys()
print("Phonebook Information")
print('---------------------')
print("Name",'\t',"Phone number")
for i in k:
print(i,'\t',phonebook[i])
if ch==2:
name=input("Enter name to search:")
f=0
k=phonebook.keys()
for i in k:
if(i==name):
print("Phone number= ",phonebook[i])
f=1
if (f==0):
print("Given name not exist")
if ch==3:
break
Output is:
******MENU\*******n
1:Delete from Dictionary
2:Search Phone number using name from Dictionary
3:Exit
Assignment 6:
Write a menu driven program in python to do following
MENU
4. Reverse String
5. Check Whether string is Palindrome
6. Make half string in Uppercase
7. Exit
Ans:
while True:
print("******MENU*******\n")
print('1:Reverse String')
print('2:Check whether string is palindrome')
print('3:Make half string in Uppercase')
print('4:Exit\n')
ch=int(input('Enter your choice:'))
if ch==1:
st = input('Enter String:')
print(st[::-1])
if ch==2:
st = input('Enter String:')
if st==st[::-1]:
print('This string is palindrome')
else:
print('String is not palindrome')
if ch==3:
st = input('Enter String:')
print("The original string is : " + str(st))
# computing half index
hlf_idx = len(st) // 2
res = ''
for idx in range(len(st)):
# uppercasing later half
if idx >= hlf_idx:
res += st[idx].upper()
else :
res += st[idx]
# printing result
print("The resultant string : " + str(res))
if ch==4:
break
Output is:
******MENU*******
1:Reverse String
2:Check whether string is palindrome
3:Make half string in Uppercase
4:Exit
Assignment 7:
Write a program to read a list of n integers (positive as well as negative). Create two
new lists, one having all positive numbers with sum and the other having all negative
numbers with sum from the given list.
Ans:
list1=[]
plist1=[]
nlist1=[]
sum=0
sum1=0
n=int(input('how many elements u want in list:'))
for i in range(0,n):
a=int(input('enter item in list:'))
list1.append(a)
print('Original list is:',list1)
for i in range(0,n):
if list1[i]<0:
nlist1.append(list1[i])
sum=sum+list1[i]
else:
plist1.append(list1[i])
sum1=sum1+list1[i]
print('positive list is;',plist1)
print('sum of +ve numbers:',sum1)
print('Negative list is;',nlist1)
print('sum of -ve numbers:',sum)
Output is:
how many elements u want in list:4
enter item in list:3
enter item in list:2
enter item in list:-1
enter item in list:-1
Original list is: [3, 2, -1, -1]
positive list is; [3, 2]
sum of +ve numbers: 5
Negative list is; [-1, -1]
sum of -ve numbers: -2
Assignment 8:
Ans:
a=[]
n=int(input('how many elements u want in list:'))
for i in range(0,n):
n1=int(input('enter item in list:'))
a.append(n1)
print('Original list is:',a)
print('List after removing duplicate elements:')
dup_items = set()
uniq_items = []
for x in a:
if x not in dup_items:
uniq_items.append(x)
dup_items.add(x)
print(dup_items)
Output is:
how many elements u want in list:5
enter item in list:34
enter item in list:2
enter item in list:34
enter item in list:2
enter item in list:1
Original list is: [34, 2, 34, 2, 1]
List after removing duplicate elements:
{1, 34, 2}
Assignment 9:
Write a python code using function to search an element in a list using Binary search method.
Ans:
def binary_search(list1, n):
low = 0
high = len(list1) - 1
mid = 0
# Function call
result = binary_search(list1, x)
if result != -1:
print("Element is present at index", str(result),'and at position:',str(result+1))
else:
print("Element is not present in list1")
Output is:
how many elements u want in list:5
enter item in ascending/descending order in list:20
enter item in ascending/descending order in list:15
enter item in ascending/descending order in list:14
enter item in ascending/descending order in list:13
enter item in ascending/descending order in list:12
Enter item to search:14
Element is present at index 2 and at position: 3
Assignment 10:
Write a menu driven program to generate random numbers given in specific range
and to display calendar after giving month and year.
MENU
1. Generate Random numbers
2. Calender of a month
3.Exit
Ans:
# Program to display calendar of the given month and year
import random
import calendar
while True:
print("******MENU*******\n")
print('1:Random Number generators')
print('2:Calender of a month')
print('3:Exit\n')
ch=int(input('Enter your choice:'))
if ch==1:
num = 10
start = 20
end = 40
res = []
for j in range(num):
res.append(random.randint(start, end))
print(res)
if ch==2:
yy = int(input("Enter year: "))
mm = int(input("Enter month: "))
print(calendar.month(yy, mm))
if ch==3:
break
Output is:
******MENU*******
******MENU*******
Assignment 11:
Write a python program to read and display file content line by line with each word
separated by #.
Ans:
file=input('Enter the file: ')
f =open( file,'r')
item=[]
for line in f:
words=line.split()
for i in words:
item.append(i)
print('#'.join(item))
Output is:
Enter the file: i.txt
i#like#india
Assignment 12:
Write a python program Read a text file and display the number of
vowels/consonants/uppercase/lowercase characters in the file.
Ans:
def cnt():
f=open('i.txt','r')
cont=f.read()
v=0
c=0
lcl=0
ucl=0
for ch in cont:
if(ch.islower()):
lcl=lcl+1
elif (ch.isupper()):
ucl=ucl+1
if (ch in['a','e','i','o','u'] or ch in['A','E','I','O','U']):
v=v+1
elif (ch in ['b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z'] or ch in['B', 'C',
'D', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'V', 'W','X', 'Y','Z']):
c=c+1
f.close()
print('Vowels are:',v)
print('Consonents are:',c)
print('Lowercase letters are:',lcl)
print('Uppercase letters are:',ucl)
cnt()
Output is:
Vowels are: 6
Consonents are: 4
Lowercase letters are: 10
Uppercase letters are: 0
Assignment 13:
Write a python code that accepts a filename, and copies all lines that do not start with
a lowercase letter from the first file into the second.
Ans:
Output is:
Assignment 14:
Write a python program to remove all the lines that contain the character ‘a’ in a file
and write it to another file.
Ans:
fo=open("hp.txt","w")
fo.write("Harry Potter")
fo.write("There is a difference in all harry potter books\nWe can see it as harry
grows\nthe books were written by J.K rowling ")
fo.close()
fo=open('hp.txt','r')
fi=open('writehp.txt','w')
l=fo.readlines()
for i in l:
if 'a' in i:
i=i.replace('a','')
fi.write(i)
fi.close()
fo.close()
Output is:
Assignment 15:
Write a python program to create a binary file with name and roll number. Search for
a given roll number and display name, if not found display appropriate message.
Ans:
import pickle
while True:
rollno = int(input('Enter roll number:'))
name = input('Enter Name:')
flag = True
except EOFError:
break
if flag == False:
print('No Records found')
f.close()
Output is:
Enter roll number:1
Enter Name:APARNA DHIRDE
Wish to enter more record (Y/N):Y
Enter roll number:2
Enter Name:MANGESH
Wish to enter more record (Y/N):Y
Enter roll number:3
Enter Name:VEERA
Wish to enter more record (Y/N):N
Enter rollno to be searched=2
Roll Num: 2
Name: MANGESH
Assignment 16:
Write a python program to create a binary file with roll number, name and marks.
Input a roll number and update name and marks
Ans:
import pickle
while True:
rollno = int(input('Enter roll number:'))
name = input('Enter Name:')
marks = int(input('Enter Marks:'))
#Creating the dictionary
rec = {'Rollno':rollno,'Name':name,'Marks':marks}
#Writing the Dictionary
f = open('student1.dat','ab')
pickle.dump(rec,f)
ch=input('Wish to enter more record (Y/N):')
if ch=='N' or ch=='n':
break
f.close()
f=open('student1.dat','rb+')
found=0
f.close()
Output is:
Enter roll number:1
Enter Name:ASHWINI UPARE
Enter Marks:456
Wish to enter more record (Y/N):Y
Enter roll number:2
Enter Name:MANOJ PATIL
Enter Marks:400
Wish to enter more record (Y/N):N
Enter roll no to search :2
Current name is: MANOJ PATIL
Current Marks are: 400
Enter new name:MANOJ ASHOK PATIL
Enter new marks:500
Record updated
Assignment 17:
Write a menu driven python program to create a CSV file by entering dept-id, name
and city, read and search the record for given dept-id.
MENU
1. Create csv
2. Search record as per dept no
3.Exit
Ans:
import csv
while True:
print('*** MENU ***\n')
print('1: create csv file')
print('2: Search as per id')
print('3: Exit')
ch=int(input('Enter choice:'))
if ch==1:
f=open('dept.csv','a')
mywriter=csv.writer(f,delimiter=',')
ans='y'
while ans.lower()=='y':
rno=int(input('Enter dept no:'))
name=input('Enter dept name:')
clas=input('Enter city:')
mywriter.writerow([rno,name,clas])
print('## Data Saved ##')
ans=input('Add More?:')
f.close()
if ch==2:
print("Search a Record")
print("===================")
f=open('dept.csv','r',newline='\r\n') #Remove new line character from output
r=input('Enter DEPT no you want to search:')
s=csv.reader(f)
for rec in s:
if rec[0]==r:
print("Rollno=",rec[0])
print("Name=",rec[1])
print("Marks=",rec[2])
f.close()
if ch==3:
break
Output is:
*** MENU ***
Assignment 18:
Write a Menu driven program in python to count spaces, digits, words and lines from
text file try.txt
Ans:
while True:
print('*** MENU ***\n')
print('1: count spaces')
print('2: count digits')
print('3: count words')
print('4: count lines')
print('5: exit')
ch=int(input('enter your choice:'))
if ch==1:
F1=open('abc.txt', 'r')
c=0
F=F1.read()
for letter in F:
if( letter.isspace( )):
c=c+1
print('No. of spaces are:',c)
F1.close()
if ch==2:
c=0
F1=open('abc.txt', 'r')
F=F1.read()
for letter in F:
if( letter.isdigit( )):
c=c+1
F1.close()
if ch==3:
f=open("abc.txt","r")
linesList=f.readlines()
count=0
for line in linesList:
wordsList=line.split()
print(wordsList)
count = count+ len(wordsList)
print("The number of words in this file are : ",count)
f.close()
if ch==4:
count =0
f=open("abc.txt","r")
data=f.readlines()
print(data)
for line in data:
count=count+1
print("Number of lines : " ,count)
f.close()
if ch==5:
break
Output is:
*** MENU ***
1: count spaces
2: count digits
3: count words
4: count lines
5: exit
enter your choice:1
No. of spaces are: 8
*** MENU ***
1: count spaces
2: count digits
3: count words
4: count lines
5: exit
enter your choice:2
No. of digits are: 4
*** MENU ***
1: count spaces
2: count digits
3: count words
4: count lines
5: exit
enter your choice:3
['Sky', 'is', 'blue', '2021.']
['i', 'like', 'rainy', 'season.']
The number of words in this file are : 8
*** MENU ***
1: count spaces
2: count digits
3: count words
4: count lines
5: exit
enter your choice:4
['Sky is blue 2021.\n', 'i like rainy season.\n']
Number of lines : 2
*** MENU ***
1: count spaces
2: count digits
3: count words
4: count lines
5: exit
enter your choice:5
>>>