SHANTINIKETAN WORLD SCHOOL (10+2), ALIGARH
CLASS 12
COMPUTER SCIENCE (083)
PRACTICAL PROGRAM
#prog 1: program to sort a list using Bubble sort (Function).
def bubblesort(a, number):
for i in range(number -1):
for j in range(number - i - 1):
if(a[j] > a[j + 1]):
temp = a[j]
a[j] = a[j + 1]
a[j + 1] = temp
a = []
number = int(input("Please Enter the Total Number of Elements : "))
for i in range(number):
value = int(input("Please enter the %d Element of List1 : " %i))
a.append(value)
bubblesort(a, number)
print("The Sorted List in Ascending Order : ", a)
OUTPUT:
Please Enter the Total Number of Elements : 5
Please enter the 0 Element of List1 : 4
Please enter the 1 Element of List1 : 6
Please enter the 2 Element of List1 : 7
Please enter the 3 Element of List1 : 2
Please enter the 4 Element of List1 : 7
The Sorted List in Ascending Order : [2, 4, 6, 7, 7]
# Prog 2: Program to sort a sequence using insertion sort (Function).
def insertionSort(nlist):
for index in range(1,len(nlist)):
currentvalue = nlist[index]
position = index
while position>0 and nlist[position-1]>currentvalue:
nlist[position]=nlist[position-1]
position = position-1
nlist[position]=currentvalue
nlist = [14,46,43,27,57,41,45,21,70]
insertionSort(nlist)
print(nlist)
OUTPUT:
[14, 21, 27, 41, 43, 45, 46, 57, 70]
# Prog 3: write a program that generates 4 terms of an AP by providing initial and step values to a function
that returns first four terms of the series.
def retseries(init, step):
return init, init+step, init+2*step, init+3*step
ini=int(input("enter initial value of the AP series: "))
st=int(input("enter step value of the AP series: "))
print("series with initial value of ",ini,"& step value", st, "goes as:")
t1,t2,t3, t4=retseries(ini,st)
print(t1,t2,t3, t4)
Output:
enter initial value of the AP series: 0
enter step value of the AP series: 1
series with initial value of 0 & step value 1 goes as:
0123
# Prog 4: Write a function lshift (arr,n)in python, which accepts a list arr of numbers and n is a numeric
value by which all elements of the list are shifted to left.
def lshift(arr, n):
l=len(arr)
for x in range(0,n):
y=arr[0]
for i in range(0, l-1):
arr[i]=arr[i+1]
arr[l-1]=y
print(arr)
arr=[10,20,30,40,12,11]
n=2
lshift(arr, n)
Output:
[30, 40, 12, 11, 10, 20]
#Prog 5: Write a program for random number generator that generates random numbers between 1 and 6
(simulates a dice).
import random
lst=[]
def dice():
for i in range(6):
a=(random.random()*6)
lst.append(a)
print(lst)
dice()
Output:
[0.6177390869630788, 2.7575067869398753, 0.697335383760578, 2.148665748830594, 3.006708430676486,
2.609079666683953]
#Prog 6: Displaying the size of a file after removing EOL characters, leading and trailing white spaces and
blank lines.
myfile=open(r'E:\poem.txt', "r")
str1= " "
size=0
tsize=0
while str1:
str1=myfile.readline()
tsize=tsize+len(str1)
size=size+len(str1)
print("Size of file after removing all EOL characters & blank lines:", size)
print(“the Total size of the file: ”, tsize)
myfile.close()
Output:
Size of file after removing all EOL characters & blank lines:360
The Total size of the file: 387
#Prog 7: Write a program to display the number of lines in the file.
myfile=open(r'E:\poem.txt', "r")
s=myfile.readlines()
linecount=len(s)
print("Number of lines in poem.txt is", linecount)
myfile.close()
Output:
Number of lines in poem.txt is 18
Prog 8: Write a Program to get roll numbers, names and marks of the students of a class(get from user)
and store these details in the file called “Marks.det”.
count=int(input(“How many students are there in the class?”))
fileout=open(“Marks.det”, “w”)
for i in range(count):
print(“Enter details for student”, (i+1), “below:”)
rollno=int(input(“Rollno: ”))
name=input(“Name: ”)
marks=float(input(“Marks: ”))
rec=str(rollno)+ “,”+name+ “,”+str(marks)+ ‘\n’
fileout.write(rec)
fileout.close()
Output:
How many students are there in the class? 3
Enter details for student 1 below:
Rollno: 12
Name: Hazel
Marks: 67.75
Enter details for student 2 below:
Rollno: 15
Name: jiya
Marks: 78.5
Enter details for student 2 below:
Rollno: 16
Name: Noor
Marks: 68.9
#Prog 9: Write a program to add two more students’ details to the file created in program 8.
fileout=open(“Marks.det”, “a”)
for i in range(2):
print(“Enter details for student”, (i+1), “below:”)
rollno=int(input(“Rollno: ”))
name=input(“Name: ”)
marks=float(input(“Marks: ”))
rec=str(rollno)+ “,”+name+ “,”+str(marks)+ ‘\n’
fileout.write(rec)
fileout.close()
Output:
Enter details for student 1 below:
Rollno: 17
Name: Akshar
Marks: 78.9
Enter details for student 2 below:
Rollno: 23
Name: Jivin
Marks: 89.5
#Prog 10: Write a program to read a text file line and display each word separated by a "#".
myfile=open("Answer.txt","r")
line=" " #intially stored a space (a non-None value)
while line:
line=myfile.readline() #one line read from file
for word in line.split():
print(word,end='#')
print()
#close the file
myfile.close()
Output:
I#am#Computer#Science#
Class#XII#
Hello#
#Prog 11: write a program to read a text file and display the count of vowels and consonants in the files.
myfile=open("Answer.txt","r")
ch= " "
vcount=0
ccount=0
while ch:
ch=myfile.read(1)
if ch in ['a','A', 'e', 'E', 'i', 'I', 'o', 'O', 'u','U']:
vcount=vcount+1
else:
ccount=ccount+1
print("vowelsin the file: ", vcount)
print ("Consonants in the file: ", ccount)
#close the file
myfile.close()
Output:
Vowels in the file: 13
Consonants in the file: 25
# Prog 12: Write a program to get student data (rollno, name and marks) from user and write onto a binary
file.
import pickle
stu={}
stufile=open('stu.dat', 'wb') #open file
ans='y'
while ans=='y':
rno=int(input("Enter roll number: "))
name=input("Enter name: ")
marks=float (input("Enter marks: "))
stu['Rollno']=rno
stu['Name']=name
stu['Marks']=marks
#now write into the file
pickle.dump(stu, stufile)
ans=input("Want to enter more records?(y/n....)")
stufile.close() #close file
Output:
Enter roll number: 1
Enter name: riye
Enter marks: 66
# prog 13: Write a program to append student records to file created in previous program, by getting
data from user.
# prog 14: Write a program to open the file created in program 12 and 13 and display the student
records stored in it.
# Prog 15: Write a program to open file Stu.dat and search for records with roll no numbers as 12 or 14. if
found, display the records.
import pickle
stu={}
found=False
fin=open ('Stu.dat', 'rb')
searchkeys=[12,13]
try:
print("Searching in file Stu.dat....")
while True:
stu=pickle.load(fin)
if stu['Rollno'] in searchkeys:
print(stu)
found=True
except EOFError:
if found==False:
print("No such records found in the file")
else:
print("search successfull.")
fin.close()
# Prog 16: Read file Stu.dat created in earlier and display records having >81.
# Prog 17: Write a program to create a CSV file to store student data (Rollno, Name, Marks). obtain data
from user and write 5 records into the file.
import csv
fh=open("Student.csv", "w")
stuwriter=csv.writer(fh)
stuwriter.writerow(['Rollno', 'name', 'Marks'])
for i in range(5):
print("Student record", (i+1))
rollno=int(input("Enter rollno:"))
name=input("Enter name:")
marks=float(input("Enter marks:"))
sturec=[rollno,name, marks]
stuwriter.writerow(sturec)
fh.close()
Output:
Student record 1
Enter rollno:11
Enter name:riya
Enter marks:99
Student record 2
Enter rollno:12
Enter name:rohit
Enter marks:89
Student record 3
Enter rollno:13
Enter name:uday
Enter marks:77
Student record 4
Enter rollno:14
Enter name:rashmi
Enter marks:89
Student record 5
Enter rollno:15
Enter name:tanisha
Enter marks:9
# Prog 18: The data of winnes of four rounds of a competitive programming competition is given as:
#['Name', 'Points', 'Rank']
#['Shradha', 4500, 23]
#['Nishchay', 4800, 25]
#['Adi', 5100, 14]
# Write a program to create a csv file(compresult.csv) and write the above data into it.
import csv
fh=open("compresult.csv","w")
cwriter=csv.writer(fh)
compdata=[['Name', 'Points', 'Rank'],['Shradha',4500,23],['Nishchay',4800,31],['Ali',4500,25],['Adi',5100,14]]
cwriter.writerows(compdata)
fh.close()
Output:
Name Points Rank
Shradha 4500 23
Nishchay 4800 31
Ali 4500 25
Adi 5100 14
# Prog 19: a. Write a program to create a CSV file by suppressing the EOL translation.
b. Write a program to read and display the contents of Employee.csv created in the previous program.
Prog 20: Write a Program to implement stack operations.
def isEmpty(stk):
if stk==[]:
return True
else:
return False
def Push(stk,item):
stk.append(item)
top=len(stk)-1
def Pop(stk):
if isEmpty(stk):
return"Underflow"
else:
item=stk.pop()
if len(stk)==0:
top=None
else:
top=len(stk)-1
return item
def Peek(stk):
if isEmpty(stk):
return"Underflow"
else:
top=len(stk)-1
return stk[top]
def Display(stk):
if isEmpty(stk):
print("Stack empty")
else:
top=len(stk)-1
print(stk[top],"<-top")
for a in range(top-1,-1,-1):
print(stk[a])
#_main_
stack=[] #Initially Stack is empty
top= None
while True:
print("STACKOPERATIONS:")
print("1.Push")
print("2.Pop")
print("3.Peak")
print("4.Displace Stack")
print("5.Exit")
ch=int(input("Enter your choice(1-5):"))
if ch==1:
item=int(input("Enter item:"))
Push(stack,item)
elif ch==2:
item=Pop(stack)
if item=="Underflow":
print("Underflow!Stack is Emplty!")
else:
print("Pop item is",item)
elif ch==3:
item=Peek(stack)
if item=="Underflow":
print("Underflow! Stack is empty!")
else:
print("Topmost item is",item)
elif ch==4:
Display(stack)
elif ch==5:
break
else:
print("Invalid Choice!")
Prog 21: Write a program to implement a stack for these book-details (book name, book name). That is,
now each item node of the stack contains two types of information- a bookno, and its name. Just
implement Push and display operations.