0% found this document useful (0 votes)
45 views10 pages

Class 12 Computer Science Practical Programs

The document contains 20 programming problems related to computer science concepts like sorting, searching, file handling, and stacks. The problems cover basic operations like bubble sort, insertion sort, arithmetic progression, left shift of an array, random number generation, and file operations like reading, writing, appending, and searching data. Problems 18-20 focus on creating and manipulating CSV files to store competition results and employee data. The programs demonstrate fundamental programming concepts.

Uploaded by

lavyasharma566
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
45 views10 pages

Class 12 Computer Science Practical Programs

The document contains 20 programming problems related to computer science concepts like sorting, searching, file handling, and stacks. The problems cover basic operations like bubble sort, insertion sort, arithmetic progression, left shift of an array, random number generation, and file operations like reading, writing, appending, and searching data. Problems 18-20 focus on creating and manipulating CSV files to store competition results and employee data. The programs demonstrate fundamental programming concepts.

Uploaded by

lavyasharma566
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

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))

[Link](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=([Link]()*6)

[Link](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:\[Link]', "r")

str1= " "

size=0

tsize=0

while str1:

str1=[Link]()

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)

[Link]()

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:\[Link]', "r")

s=[Link]()

linecount=len(s)

print("Number of lines in [Link] is", linecount)

[Link]()

Output:
Number of lines in [Link] 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 “[Link]”.
count=int(input(“How many students are there in the class?”))
fileout=open(“[Link]”, “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’
[Link](rec)

[Link]()
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(“[Link]”, “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’
[Link](rec)
[Link]()

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("[Link]","r")
line=" " #intially stored a space (a non-None value)
while line:
line=[Link]() #one line read from file

for word in [Link]():


print(word,end='#')
print()
#close the file
[Link]()

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("[Link]","r")

ch= " "


vcount=0
ccount=0
while ch:
ch=[Link](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
[Link]()

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('[Link]', '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

[Link](stu, stufile)
ans=input("Want to enter more records?(y/n....)")
[Link]() #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 [Link] and search for records with roll no numbers as 12 or 14. if
found, display the records.
import pickle
stu={}
found=False
fin=open ('[Link]', 'rb')
searchkeys=[12,13]
try:
print("Searching in file [Link]....")
while True:
stu=[Link](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.")
[Link]()

# Prog 16: Read file [Link] 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("[Link]", "w")
stuwriter=[Link](fh)
[Link](['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]
[Link](sturec)
[Link]()
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([Link]) and write the above data into it.
import csv
fh=open("[Link]","w")
cwriter=[Link](fh)
compdata=[['Name', 'Points', 'Rank'],['Shradha',4500,23],['Nishchay',4800,31],['Ali',4500,25],['Adi',5100,14]]
[Link](compdata)
[Link]()

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 [Link] 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):
[Link](item)
top=len(stk)-1

def Pop(stk):
if isEmpty(stk):
return"Underflow"
else:
item=[Link]()
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("[Link]")
print("[Link]")
print("[Link]")
print("[Link] Stack")
print("[Link]")
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.

Common questions

Powered by AI

Text file manipulation shown involves reading and writing strings, line counts, and character analysis, suitable for human-readable content. Binary files, on the other hand, use serialization with modules like pickle, which are better for complex structured data requiring efficient storage and retrieval. Text files are ideal for simple or standard I/O tasks, whereas binary files handle larger, more complex data structures, maintain datatype integrity, and prevent data loss during transfer or storage .

The document shows various file handling operations such as opening files, reading lines, and counting specific elements like end-of-line (EOL) characters, vowels, and consonants. It demonstrates reading a file line by line, as well as writing data into files, using functions such as open(), read(), and write(). The examples illustrate storing and manipulating text data in Python, highlighting concepts such as removing white spaces or counting lines .

Insertion sort can be more efficient than bubble sort because it sorts the list as it builds the sorted sequence. It reduces unnecessary comparisons after moving an element by performing fewer swaps. When dealing with small datasets or partially sorted lists, insertion sort may require fewer comparisons and shifts, while bubble sort continues comparing all elements without leveraging any sorted order .

Storing student data in a binary file, as demonstrated, allows for efficient data serialization. Using the pickle module, complex data structures such as dictionaries storing student records can be serialized and saved for persistent storage. Binary files preserve data integrity and can be more space-efficient than text files, especially for complex data, making recovery and manipulation of data systematic and less error-prone .

The stack implementation demonstrates fundamental computer science principles such as abstract data types and stack operations (Push, Pop, Peek, and Display). The implementation follows LIFO order, ensuring that the most recently added elements are accessed first. The use of list operations to implement stack actions aligns with typical practice in developing data structures, highlighting understanding of stack operations' behavior within broader computational problems .

A stack implementation for managing book details would involve defining a stack where each element is a tuple or a dictionary containing two fields: 'book number' and 'book name'. The stack operations would include Push, to add books to the stack, and Display, to show the current stack status. Push would append a new book as a tuple (book_no, book_name) to the stack list, and Display would provide a structured output of the book list from top to bottom, conforming to the LIFO (Last In, First Out) principle .

The purpose of an arithmetic progression (AP) sequence generator is to provide a sequence of numbers in which the difference between consecutive terms, called the step, is constant. The generator function takes initial and step values to compute the first four terms of the sequence. This is useful in demonstrating iterative patterns and can be applied in a variety of mathematical and real-world scenarios requiring a predictable change in sequence .

The left shift operation involves moving each element of the array to its left by the specified number of positions. In the implementation, the first element is temporarily stored, and elements from index 1 to n-1 are shifted to the left by one position. The last position in the array is replaced by the temporarily stored element. This process is repeated for the number of positions indicated, effectively rotating the array to the left .

The current implementation uses random.random() * 6, which generates floating-point numbers and does not accurately simulate rolling a dice, as dice rolls should result in an integer between 1 and 6. This can be improved by using random.randint(1, 6) to generate true integer dice values, ensuring the simulation adheres to the expected outcome of a dice roll .

The bubble sort algorithm repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order. This process is repeated for each element until the list is sorted. The algorithm moves the largest unsorted element to its correct position on each pass, and this is continued until no more swaps are needed, indicating that the list is sorted .

You might also like