0% found this document useful (0 votes)
34 views29 pages

User Defined Module Aryan

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

User Defined Module Aryan

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

CENTRAL BOARD OF SECONDARY EDUCATION

COMPUTER SCIENCE PROJECT


PROJECT TITLE:
User-Defined Modules

SUBMITTED BY:

Name: Aryan Pratap Singh


Class: 12th
Section: B1
Roll Number: 11

SUBMITTED TO:

Subject Teacher: Mrs. Bindu Vasudevan

SCHOOL NAME:

St. Mary's Convent School, Gajraula

ACADEMIC YEAR:

2024-2025

MODULE OF USER DEFINED

‘’’ 1.WRITE A FUNCTION ALTER(A, N) IN PYTHON, WHICH SHOULD


CHANGE ALL THE MULTIPLES OF 5 IN THE LIST TO 5 AND REST OF THE
ELEMENTS AS 0.’’’
def alter(a, n):
for i in range(n):
if a[i] % 5 == 0:
a[i] = 5
else:
a[i] = 0
print("List after alteration:", a)

‘’’2. Shift all elements to the next position, and the last element to the
first’’’
def convert(t, n):
x = t[-1] # Store the last element
for i in range(n-1, 0, -1):
t[i] = t[i-1] # Shift elements to the right
t[0] = x # Place the last element at the first position
print("List after conversion:", t)

‘’’3. Double the number’’’


def dbl(n):
a=n*2
print("Double of the number:", a)

‘’’4. Calculate the area of a square’’’


def sarea(s):
a=s*s
print("Area of square:", a)

‘’’ 5. Calculate the area of a circle’’’


def carea(r):
a = 3.14 * r * r
print("Area of circle:", a)

‘’’# 6. Calculate the sum of two numbers’’’


def fun(a, b):
c=a+b
print("Sum of the two numbers is", c)

‘’’7. Calculate the sum of digits of an input number’’’


def dsum(n):
s=0
n = str(n)
for i in n:
s += int(i)
print("Sum of digits:", s)

‘’’8. Check whether a number is prime or not’’’


def chkprime(n):
k=0
for i in range(2, n):
if n % i == 0:
k=1
if k == 0:
print("It is a prime number")
else:
print("It is not a prime number")

‘’’9. Reverse a string’’’


def rev(s):
s = s[::-1]
return s

‘’’10. Print Fibonacci series up to n numbers’’’


def fibo():
n = int(input("Enter a number: "))
a, b = 0, 1
for i in range(n):
c=a+b
b=a
a=c
print(a, end=" ")
print()

‘’’11. Arrange a list in ascending order using bubble sort’’’


def bsort(l):
for i in range(len(l)):
for j in range(len(l) - 1 - i):
if l[j] > l[j + 1]:
l[j], l[j + 1] = l[j + 1], l[j]
print("Arranged list:", l)

‘’’12. Check whether a number is Armstrong or not’’’


def arm():
n = int(input("Enter a number: "))
a=n
s=0
while n > 0:
k = n % 10
s += k ** 3
n //= 10
if s == a:
print("It is an Armstrong number")
else:
print("No, it is not an Armstrong number")

‘’’13. Calculate the square of any number’’’


def sqr(n):
s=n*n
print("Square of given number:", s)

‘’’14. Find the maximum number’’’


def max(a, b, c):
if a > b and a > c:
print("Maximum number:", a)
elif b > a and b > c:
print("Maximum number:", b)
else:
print("Maximum number:", c)

‘’’15. Merge two lists’’’


def lmerge(x, y):
s=x+y
print("Merged list:", s)

‘’’16. Multiplication table of a number’’’


def mtable(n):
for i in range(1, 11):
print(f"{n} x {i} = {n * i}")

‘’’17. Get sum of natural numbers till n’’’


def nsum(n):
s=0
for i in range(1, n + 1):
s += i
print("Sum of natural numbers:", s)

‘’’18. Print prime numbers till n’’’


def pprime(n):
for i in range(2, n + 1):
k=1
for j in range(2, i):
if i % j == 0:
k=0
if k == 1:
print(i)

‘’’19. Count number of alphabets, digits, and special characters in a


string’’’
def count(s):
a, d, sp = 0, 0, 0
for i in s:
if i.isalpha():
a += 1
elif i.isdigit():
d += 1
else:
sp += 1
print("Number of alphabets:", a)
print("Number of digits:", d)
print("Number of special characters:", sp)

‘’’20. Sort a list using insertion sort’’’


def isort(l):
for i in range(1, len(l)):
t = l[i]
j=i-1
while j >= 0 and t < l[j]:
l[j + 1] = l[j]
j -= 1
l[j + 1] = t
print("Sorted list:", l)

‘’’CALLING STATEMENTS:’’’
d = eval(input("Enter a list: "))
print("Original list:", d)
r = len(d)
alter(d, r)

d = eval(input("Enter another list: "))


print("Original list:", d)
r = len(d)
convert(d, r)
n = int(input("Enter a number: "))
dbl(n)

s = float(input("Enter side of a square: "))


sarea(s)

r = float(input("Enter radius of a circle: "))


carea(r)

a = int(input("Enter first number: "))


b = int(input("Enter second number: "))
fun(a, b)

n = int(input("Enter a number: "))


dsum(n)

n = int(input("Enter a number: "))


chkprime(n)

s = input("Enter a string: ")


print("Reversed string:", rev(s))

fibo()

l = eval(input("Enter a list: "))


bsort(l)
arm()

n = int(input("Enter a number: "))


sqr(n)

a = int(input("Enter first number: "))


b = int(input("Enter second number: "))
c = int(input("Enter third number: "))
max(a, b, c)

x = eval(input("Enter first list: "))


y = eval(input("Enter second list: "))
lmerge(x, y)

a = int(input("Enter a number: "))


mtable(a)

n = int(input("Enter a number: "))


nsum(n)

n = int(input("Enter a number: "))


pprime(n)

s = input("Enter a string: ")


count(s)

l = eval(input("Enter a list to be sorted: "))


isort(l)
‘’’OUTPUTS:’’’
ORIGINAL LIST [10, 14, 15, 21] 11
LIST AFTER ALTERATION[5,0,5,0]
ORIGINAL LIST [10, 14, 11, 21]
LIST AFTER CONVERSION [21, 10, 14, 11]
ENTER NO1: 34
ENTER NO2: 43
SUM OF 2 NO.S IS 77
ENTER A STRING - VINAYAK
REVERSED STRING – KAYANIV
ENTER A NO.-45
SUM OF DIGIT – 9
ENTER A NO.-4
IT IS NOT A PRIME NUMBER
ENTER A NO.-5
IT IS A PRIME NUMBER
ENTER A NUMBER -5
11235
ENTER A NUMBER -4 12
1123
ENTER A LIST[1,2,3,7,87,96,96,9787]
ARRANGED LIST: [1, 2, 3, 7, 87, 96, 96, 9787]
ENTER A NO-1234321
IT IS A PALINDROME
ENTER NO.5
SQUARE OF GIVEN NUMBER: 25
ENTER SIDE OF SQUARE:5
AREA OF SQUARE: 25.0
ENTER RADIUS:7
AREA OF CIRCLE: 153.86
ENTER NUMBER:5
DOUBLE OF THE NUMBER. 10
ENTER 1ST NUMBER:56
ENTER 2ND NUMBER:78
ENTER 3RD NUMBER:90
MAXIMUM NUMBER:90
ENTER A NUMBER:5
5
10
15
20
25
30
35
40
45
50
ENTER 1ST LIST:[1,2,3]
ENTER 2ND LIST:[4,5,6]
[1, 2, 3, 4, 5, 6]
ENTER A NUMBER:10
SUM OF NATURAL NUMBER : 55
ENTER A NUMBER:10
2
3
5
7
ENTER A STRING VINAYAK_17379
NO. OF ALPHABETS: 7
NO. OF DIGITS: 5
NO. OF SPECIAL CHARACTERS: 1
ENTER LIST TO BE SORTED :[5,3,6,2,7,8]
[2, 3, 5, 6, 7, 8]
#DATA HANDLING:-
#BINARY FILES
#21. Write a function to create item details in a file “Item.dat”.
import pickle
def create ():
d={}
xf=open("Item.dat","wb")
wish='y'
while wish=='y':
Itno=int(input("Enter an item no."))
desc=input("Enter description")
Qty=int(input("Enter quantity"))
rate=float(input("Enter rate"))
d['Item no.']=Itno
d['Descrip']=desc
d['Qty']=Qty
d['Rate']=rate
pickle.dump(d,xf)
wish=input("Add Y/N")
xf.close()
create()
#OUTPUT
Enter an item no.1
Enter descriptionChair
Enter quantity40
Enter rate160
Add Y/Ny
Enter an item no.2
Enter descriptionTable
Enter quantity65
Enter rate250
Add Y/Nn
‘’’22. Write a function display() to display the contents of the file from
“Item.dat”.’’’
import pickle
def display():
d={}
xf = open("Item.dat", "rb")
try:
while True:
d = pickle.load(xf)
print(d)
except EOFError:
xf.close()
display()
#OUTPUT
{'Item no.': 1, 'Descrip': 'Chair', 'Qty': 40, 'Rate': 160.0}
{'Item no.': 2, 'Descrip': 'Table', 'Qty': 65, 'Rate': 250.0}
‘’’23. Write a function to search an item no. entered by the users if
found display the contents otherwise display not found.’’’
import pickle
def search():
k=0
d={}
xf = open("Item.dat", "rb")
N=int(input("Enter the Item no. to be searched"))
try:
while True:
d = pickle.load(xf)
if d["Item no."]==N:
k=1
print(d)
except EOFError:
if k==0:
print("Not found")
xf.close()
search()
#OUTPUT
Enter the Item no. to be searched2
{'Item no.': 2, 'Descrip': 'Table', 'Qty': 65, 'Rate': 250.0}
‘’’24. Write a function modify() to read a file of a specific item no.
entered by the user. It found increase the rate by 3%.’’’
import pickle
def modify():
xf = open("Item.dat", "rb+")
N = int(input("Enter Item no. to be searched and modify: "))
try:
while True:
rec = xf.tell()
d = pickle.load(xf)
if d["Item no."] == N:
d["Rate"] = d["Rate"] + d["Rate"] * 3 / 100
xf.seek(rec)
pickle.dump(d, xf)
except EOFError:
xf.close()
modify()
#OUTPUT
Enter Item no. to be searched and modify: 1
‘’’25.Write a function delfile() to remove a record which is accepted by
the user.’’’
import pickle
import os
def delfile():
k=0
xf=open("Item.dat","rb")
yf=open("temp.dat","wb")
N=int(input("Enter the Item no. to be deleted"))
d={}
try:
while True:
d=pickle.load(xf)
if d["Item no."]!=N:
pickle.dump(d,yf)
except EOFError:
xf.close()
yf.close()
os.remove("Item.dat")
os.rename("temp.dat","Item.dat")
delfile()
#OUTPUT
Enter the Item no. to be deleted1
{'Item no.': 2, 'Descrip': 'Table', 'Qty': 65, 'Rate': 250.0}
#CSV FILE:
‘’’26.WAF to create a csv file to store student data(roll no,name,marks
obtain) obtain data from user and add 5 records on to file’’’
import csv
def createCSV():
xf = open("abc.csv", "w", newline='')
obj = csv.writer(xf)
obj.writerow(["ROLL NO.", "NAME", "MARKS OBTAINED"])
n=int(input(“ENTER THE NO. OF RECORDS:”))
for i in range(n):
r = int(input("ENTER ROLL NO: "))
n = input("ENTER NAME: ")
m = float(input("ENTER MARKS OBTAINED: "))
obj.writerow([r, n, m])
xf.close()
createCSV()

#OUTPUT
ENTER THE NO. OF RECORDS:5
ENTER ROLL NO :32
ENTER NAME :VINAYAK SHARMA
ENTER MARKS OBTAINED :91.4
ENTER ROLL NO :33
ENTER NAME :VANSH SIROHI
ENTER MARKS OBTAINED :93.4
ENTER ROLL NO :34
ENTER NAME :VINEET KUMAR
ENTER MARKS OBTAINED :96.4
ENTER ROLL NO :06
ENTER NAME :AKSHAT SARAN
ENTER MARKS OBTAINED :67
ENTER ROLL NO :30
ENTER NAME :VANSH CHAUHAN
ENTER MARKS OBTAINED :85
‘’’27.WAF to display contents of file abc.csv’’’
import csv
def displayCSV():
# Open the CSV file in read mode
xf = open("ABC.CSV", "r", newline="")
rec = csv.reader(xf)
for i in rec:
print(i)
xf.close()
displayCSV()

#OUTPUT
['ROLL NO.', 'NAME', 'MARKS OBTAIN']
['32', 'VINAYAK SHARMA', '91.4']
['33', 'VANSH SIROHI', '93.4']
['34', 'VINEET KUMAR', '96.4']
['6', 'AKSHAT SARAN', '67.0']
['30', 'VANSH CHAUHAN', '85.0']
“’28.WAF to add records into file abc.csv’’’
import csv
def add():
xf=open("record.csv","a")
obj=csv.writer(xf)
wish="y"
while wish=="y":
r = int(input("ENTER ROLL NO: "))
n = input("ENTER NAME: ")
m = float(input("ENTER MARKS OBTAINED: "))
wish=input("Add choice y/n")
obj.writerow([r, n, m])
xf.close()
add()

#OUTPUT
ENTER ROLL NO: 11
ENTER NAME: ARYAN PRATAP SINGH
ENTER MARKS OBTAINED: 93.4
Add choice y/ny
ENTER ROLL NO: 16
ENTER NAME: DIVYANSHI SINGH
ENTER MARKS OBTAINED: 86.7
Add choice y/ny
ENTER ROLL NO: 30
ENTER NAME: PALAK DARMWAL
ENTER MARKS OBTAINED: 94.4
Add choice y/nn
#TEXT FILES:
‘’’29. WAF test() to read a file notes.txt, count no. of alphabets, digits
and special character.’’’
def test():
xf = open("NOTES.TXT", "r")
x = xf.read()
a=0
s=0
d=0
for i in x:
if i.isalpha(): # Check if the character is an alphabet
a=a+1
elif i.isdigit(): # Check if the character is a digit
d=d+1
else: # Count special characters (includes whitespace)
s=s+1
print("NO. OF ALPHABETS -", a)
print("NO. OF DIGITS -", d)
print("NO. OF SPECIAL CHARACTERS -", s)
xf.close()
test()

#OUTPUT
NO. OF ALPHABETS - 186
NO. OF DIGITS - 0
NO. OF SPECIL CHARACTERS - 50
‘’’30.WAF noise() to count no. of words having only 3 character in
notes.’’’
def noise():
c=0
xf = open("NOTES.TXT", "r")
x = xf.read()
y = x.split()
for i in y:
if len(i) == 3:
c += 1
print("No. of words having 3 characters -", c)
xf.close()
noise()

#OUTPUT
No. of words having 3 characters - 5
‘’’31.WAF to read a file notes.txt and print those lines which starts or
ends with 'o' or 'f'.’’’
def lprint():
xf=open("notes.txt","r")
y=xf.readlines()
for i in y:
if i[-2]=="o" or i[-2]=="f":
print(i)
lprint()
#OUTPUT
it opens and makes it available for a number of
different task.a file mode governs the type of
operations possible in opened file.it refers to

#BUBBLE SORT:-
‘’’32.WAF bsort()to arrange a list in ascending order using bubble
sort’’’
def bsort(l):
for i in range(len(l)):
for j in range(0,len(l)-i-1):
if l[j]>l[j+1]:
l[j],l[j+1]=l[j+1],l[j]
print(l)
l=eval(input("enter a list :"))
bsort(l)
#OUTPUT
enter a list :[3,5,2,1,5,6,8,3,0,4,2,0,7,8,9]
[0, 0, 1, 2, 2, 3, 3, 4, 5, 5, 6, 7, 8, 8, 9]

#INSERTION SORT:-
‘’’33.WAF isort()to arrange a list in ascending order using insertion
sort.’’’
def isort(l):
for i in range (1,len(l)):
t=l[i]
j=i-1
while t<l[j] and j>=0:
l[j+1]=l[j]
j=j-1
l[j+1]=t
print(l)
l=eval(input("enter a list :"))
isort(l)
#OUTPUT
enter a list :[3,5,2,1,5,6,8,3,0,4,2,0,7,8,9]
[0, 0, 1, 2, 2, 3, 3, 4, 5, 5, 6, 7, 8, 8, 9]

#SEARCHING

#LINEAR SEARCH:-
‘’’34.WAF TO PASS A LIST AND A NO. AND SEARCH IT IF FOUND
RETURN 1 OTHERWISE -1’’’
def linear_search(l,n):
k=-1
for i in l:
if i==n:
k=1
print(k)
l=eval(input("enter a list :"))
n=int(input("enter no. :"))
linear_search(l,n)
#OUTPUT
enter a list :[1,4,6,7]
enter no. :6
1

#BINARY SEARCH:-
‘’’35.WAF to pass a list and a no. and search it using binary search.’’’
def binary_search(l,n):
k=0
beg=0
last=len(l)-1
while beg<=last:
mid=int((beg+last)/2)
if l[mid]==n:
k=1
break
elif l[mid]>n:
last=mid-1
elif l[mid]<n:
beg=mid+1
if k==0:
print("not found")
else:
print("it is found")
l=eval(input("enter a list"))
n=int(input("enter a no."))
binary_search(l,n)
#OUTPUT
enter a list[1,2,3]
enter a no.1
it is found

#2D LIST (MATRIX)


‘’’36.WAF that passes a 2d list and find the sum of first and last
column’’’
def twod(l,r,c):
for i in range(r):
print(l[i][0]+l[i][c-1])
l=[]
r=int(input("enter no. of rows"))
c=int(input("enter no. of columns"))
for i in range(r):
row=[]
for j in range(c):
x=int(input("enter no."))
row.append(x)
l.append(row)
twod(l,r,c)
#OUTPUT
enter no. of rows2
enter no. of columns2
enter no.1
enter no.2
enter no.3
enter no.4
3
7
# Stack Implementation
'''
Stack: implemented as a list
Top: Integer having position of topmost element in stack
'''
def isempty(stk):
if stk == []:
return True
else:
return False

def push(stk, item):


stk.append(item)

def pop(stk):
if isempty(stk):
return "underflow"
else:
item = stk.pop()
return item

def peek(stk):
if isempty(stk):
return "underflow"
else:
return stk[-1]
def display(stk):
if isempty(stk):
print("stack empty")
else:
print(stk[-1], "<-top")
for a in range(len(stk)-2, -1, -1):
print(stk[a])

# MAIN
stack = []
while True:
print("Stack operation")
print("1. Push")
print("2. Pop")
print("3. Peek")
print("4. Display 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 empty!")
else:
print("Popped 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")
#OUTPUT
Stack operation
1.push
2.pop
3.peek
4.display stack
5.exit
Enter your choice(1-5):1
Enter item :1
Stack operation
1.push
2.pop
3.peek
4.display stack
5.exit
Enter your choice(1-5):1
Enter item :2
Stack operation
1.push
2.pop
3.peek
4.display stack
5.exit
Enter your choice(1-5):1
Enter item :4
Stack operation
1.push
2.pop
3.peek
4.display stack
5.exit
Enter your choice(1-5):1
Enter item :5
Stack operation
1.push
2.pop
3.peek
4.display stack
5.exit
Enter your choice(1-5):4
5 <-top
4
2
1
Stack operation
1.push
2.pop
3.peek
4.display stack
5.exit
Enter your choice(1-5):3
Topmost item is 5
Stack operation
1.push
2.pop
3.peek
4.display stack
5.exit
Enter your choice(1-5):2
Popped item is 5
Stack operation
1.push
2.pop
3.peek
4.display stack
5.exit
Enter your choice(1-5):5

You might also like