0% found this document useful (0 votes)
4 views

Project Format

Uploaded by

Saksham Narang
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Project Format

Uploaded by

Saksham Narang
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 27

SANFORT WORLD

SCHOOL

MORADABAD

COMPUTER SCIENCE
PROGRAMMING QUESTIONS

SUBMITTED TO: SUBMITTED BY:


MUDIT SIR SAKSHAM NARANG
CLASS:12TH
CERTIFICATE

This is to clarify that the content of this


project by SAKSHAM NARANG is the bona fide
work of him submitted to SANFORT WORLD
SCHOOL MORADABAD for consideration in
partial fulfilment of the requirement of CBSE
.
The original research work was carried out
by him under the guidance of Mr. Mudit in the
academic year 2024-2025.On the basis of
the declaration made by him I recommend
this project report for evaluation.

SUBJECT TEACHER:
Mr. Mudit
ACKNOWLEDGEMENT
I would like to express my heartfelt gratitude
to all those who contributed to the
completion of this project. This endeavour
wouldn’t have seen possible without the
support , guidance and encouragement I
received from various individuals and
organisations.
First and foremost , I extend my sincere
thanks to Mr. Mudit for their invaluable
guidance , patience and expertise
throughout this project. Their mentorship
and constant support in shaping our ideas
and steering us in the right direction.
Thank you everyone who directly or
indirectly supported me during this project.
Your contributions are truly invaluable and
greatly appreciated.

Saksham Narang
Class: 12th

Q1. Write a Python program to calculate the factorial of a


given number using recursion.
Code:
# Factorial of a number using recursion

def recur_factorial(n):

if n == 1:

return n

else:

return n*recur_factorial(n-1)

num = 7

# check if the number is negative

if num < 0:

print("Sorry, factorial does not exist for negative numbers")

elif num == 0:

print("The factorial of 0 is 1")

else:

print("The factorial of", num, "is", recur_factorial(num))

Output:

Q2. Create a program to check if a given string is a


palindrome.

Code:
# Program to check if a string is palindrome or not

my_str = 'aIbohPhoBiA'

# make it suitable for caseless comparison

my_str = my_str.casefold()

# reverse the string

rev_str = reversed(my_str)

# check if the string is equal to its reverse

if list(my_str) == list(rev_str):

print("The string is a palindrome.")

else:

print("The string is not a palindrome.")

Output:

Q3. Write a Python function to find the greatest common


divisor (GCD) of two numbers.

Code:
# Python program to find H.C.F of two numbers

# define a function

def compute_hcf(x, y):

# choose the smaller number

if x > y:

smaller = y

else:

smaller = x

for i in range(1, smaller+1):

if((x % i == 0) and (y % i == 0)):

hcf = i

return hcf

num1 = 54

num2 = 24

print("The H.C.F. is", compute_hcf(num1, num2))

Output:
Q4. Implement a program to count the number of vowels in a
given string

Code:
string = "counting vowels!"
vowels = "aeiouAEIOU"

count = sum(string.count(vowel) for vowel in vowels)


print(count)

Output:
5
Q5. Write a Python program to generate the Fibonacci series
up to n terms.

CODE:
# Program to display the Fibonacci sequence up to n-th term

nterms = int(input("How many terms? "))

# first two terms

n1, n2 = 0, 1

count = 0

# check if the number of terms is valid

if nterms <= 0:

print("Please enter a positive integer")

# if there is only one term, return n1

elif nterms == 1:

print("Fibonacci sequence upto",nterms,":")

print(n1)

# generate fibonacci sequence

else:

print("Fibonacci sequence:")

while count < nterms:

print(n1)

nth = n1 + n2

# update values

n1 = n2

n2 = nth

count += 1
Output:

Q6. Write a Python program to find the largest and smallest


numbers in a list.
CODE:
lst = []

num = int(input('How many numbers: '))

for n in range(num):

numbers = int(input('Enter number '))

lst.append(numbers)

print("Maximum element in the list is :", max(lst), "\nMinimum element in the list is :", min(lst))

OUTPUT:
Q7. Create a program to count the frequency of each
element in a list

CODE:
# importing the module
import collections

# initializing the list


random_list = ['A', 'A', 'B', 'C', 'B', 'D', 'D', 'A', 'B']

# using Counter to find frequency of elements


frequency = collections.Counter(random_list)

# printing the frequency


print(dict(frequency))
{'A': 3, 'B': 3, 'C': 1, 'D': 2}

OUTPUT:
{'A': 3, 'B': 3, 'C': 1, 'D': 2}

Q8. Write a Python program to merge two dictionaries and


print the resulting dictionary.
CODE:
dict_1 = {1: 'a', 2: 'b'}

dict_2 = {2: 'c', 4: 'd'}


print(dict_1 | dict_2)

OUTPUT:
{1: 'a', 2: 'c', 4: 'd'}
Q9. Implement a Python program to sort a list of tuples
based on the second element.

CODE:
a = [(1, 3), (4, 1), (2, 2)]

# Sort by second item

sorted_list = sorted(a, key=lambda x: x[1])

print("Sorted List:", sorted_list)

OUTPUT:
Sorted List: [(4, 1), (2, 2), (1, 3)]

Q10. Write a Python program to count the occurrence of


each character in a string
CODE:
my_string = "Programiz"
my_char = "r"

print(my_string.count(my_char))

OUTPUT:
2
Q11. Create a Python program to find all the substrings of a
given string.
CODE:
def get_all_substrings(input_string):
# base case 1: if the input string is empty, return an empty list
if len(input_string) == 0:
return []

# base case 2: if the input string contains only one character, return a list
with that character
elif len(input_string) == 1:
return [input_string]

# recursive case: if the input string contains multiple characters


else:
# create an empty list to store the resulting substrings
output = []

# use nested loops to generate all possible substrings of the input


string
for i in range(len(input_string)):
for j in range(i+1, len(input_string)+1):
output.append(input_string[i:j])

# recursively call the function with the input string sliced from the
second character to the end
# and concatenate the resulting list of substrings with the list
generated from the current call
return output + get_all_substrings(input_string[1:])

# test the function with an example string


my_string = "hello"
substrings = get_all_substrings(my_string)
print(substrings)

OUTPUT:
['h', 'he', 'hel', 'hell', 'hello', 'e', 'el', 'ell', 'ello', 'l', 'll', 'llo', 'l', 'lo', 'o', 'e', 'el', 'ell',
'ello', 'l', 'll', 'llo', 'l', 'lo', 'o', 'l', 'll', 'llo', 'l', 'lo', 'o', 'l', 'lo', 'o', 'o']

Q12. Write a Python program to read a file and count the


number of words, lines, and characters in it.

CODE:
# Function to count number of characters, words, spaces and lines in a file
def counter(fname):

# variable to store total word count


num_words = 0

# variable to store total line count


num_lines = 0

# variable to store total character count


num_charc = 0

# variable to store total space count


num_spaces = 0
# opening file using with() method
# so that file gets closed
# after completion of work
with open(fname, 'r') as f:

# loop to iterate file


# line by line
for line in f:

# incrementing value of num_lines with each


# iteration of loop to store total line count
num_lines += 1

# declaring a variable word and assigning its value as Y


# because every file is supposed to start with a word or a
character
word = 'Y'

# loop to iterate every


# line letter by letter
for letter in line:

# condition to check that the encountered character


# is not white space and a word
if (letter != ' ' and word == 'Y'):

# incrementing the word


# count by 1
num_words += 1

# assigning value N to variable word because


until
# space will not encounter a word can not be
completed
word = 'N'

# condition to check that the encountered character


is a white space
elif (letter == ' '):

# incrementing the space


# count by 1
num_spaces += 1

# assigning value Y to variable word because


after
# white space a word is supposed to occur
word = 'Y'

# loop to iterate every character


for i in letter:

# condition to check white space


if(i !=" " and i !="\n"):
# incrementing character
# count by 1
num_charc += 1

# printing total word count


print("Number of words in text file: ",
num_words)

# printing total line count


print("Number of lines in text file: ",
num_lines)

# printing total character count


print('Number of characters in text file: ',
num_charc)

# printing total space count


print('Number of spaces in text file: ',
num_spaces)

OUTPUT:
Number of words in text file: 25
Number of lines in text file: 4
Number of characters in text file: 91
Number of spaces in text file: 21

Q13: Implement a Python program to copy the contents of


one file to another.
CODE:
# import module
import shutil

# use copyfile()
shutil.copyfile('first.txt','second.txt')

OUTPUT:
I Am The Contents Of First File
Geeks For Geeks!

Q14. Create a Python class Student with attributes for name,


roll number, and marks in three subjects. Write a method to
calculate the average marks of the student.

Code:
class Student:
marks = []
def getData(self, rn, name, m1, m2, m3):
Student.rn = rn
Student.name = name
Student.marks.append(m1)
Student.marks.append(m2)
Student.marks.append(m3)

def displayData(self):
print ("Roll Number is: ", Student.rn)
print ("Name is: ", Student.name)
#print ("Marks in subject 1: ", Student.marks[0])
#print ("Marks in subject 2: ", Student.marks[1])
#print ("Marks in subject 3: ", Student.marks[2])
print ("Marks are: ", Student.marks)
print ("Total Marks are: ", self.total())
print ("Average Marks are: ", self.average())

def total(self):
return (Student.marks[0] + Student.marks[1] +Student.marks[2])

def average(self):
return ((Student.marks[0] + Student.marks[1] +Student.marks[2])/3)

r = int (input("Enter the roll number: "))


name = input("Enter the name: ")
m1 = int (input("Enter the marks in the first subject: "))
m2 = int (input("Enter the marks in the second subject: "))
m3 = int (input("Enter the marks in the third subject: "))

s1 = Student()
s1.getData(r, name, m1, m2, m3)
s1.displayData()

OUTPUT:
Enter the roll number: 10
Enter the name: Mahesh Huddar
Enter the marks in the first subject: 20
Enter the marks in the second subject: 30
Enter the marks in the third subject: 25
Roll Number is: 10
Name is: Mahesh Huddar
Marks are: [20, 30, 25]
Total Marks are: 75
Average Marks are: 25.0

Q15: Write a Python program to implement a stack using a


list, with operations for push, pop, and displaying the stack.

CODE:
# Created a Empty List
stack = []

# Pushing the elements in the list


stack.append(1)
stack.append(2)
stack.append(3)

print(&quot;The Stack items are :&quot;)


for i in stack:
print(stack)
stack = []

def pop(stack):
if len(stack) == 0:
return None
else:
return stack.pop()

# Pushing the elements in the list


stack.append(1)
stack.append(2)
stack.append(3)

print(&quot;Initial Stack&quot;)
print(stack)

print(&quot;Popped Element: &quot;, pop(stack))

OUTPUT:
The Stack items are :
1
2
3
Initial Stack
[1, 2, 3]
Popped Element: 3
Q17. Write a Python program to create a database named
LibraryDB and a table named Books with columns: BookID
(INT, Primary Key), Title (VARCHAR), Author (VARCHAR), and
Price (FLOAT).
CODE:
import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword"
)

mycursor = mydb.cursor()

mycursor.execute("CREATE DATABASE mydatabase")

OUTPUT:
#If this page is executed with no error, you have successfully created a
database.

CODE:
import mysql.connector

mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="mydatabase"
)

mycursor = mydb.cursor()
mycursor.execute("CREATE TABLE Books (BookID(INT,PRIMARY
KEY),Title(varchar),Aurthor(varchar),Price(FLOAT))")

OUTPUT:
#If this page is executed with no error, you have successfully created a table
named "customers".

Q18. Write a Python program to insert multiple records into


the Books table in LibraryDB. Use placeholders and a list of
tuples for the data.
CODE:
import mysql.connector

conn = mysql.connector.connect(
host='localhost',
user='username',
password='password'
database='gfg'
)

# creating cursor object


cursor = conn.cursor()
# insert command/statement
insert_st = """INSERT INTO BOOKS (BOOKID,TITLE,PRICE)
VALUES("L102","BHARAT","4200")"""

# row created
cursor.execute(insert_st)
# save changes
conn.commit()

OUTPUT:

Q19. Write a Python program to retrieve and display all


records from the Books table, ordered by Price in descending
order.
CODE:
if totalbooks > 0:
print("BOOKS")
d = {}
if book > 0:
d['ncert eng'] = (ncert eng, book.count(countncert eng)) # d[menu_item] =
(cost, order_count)
if book > 0:
d['ncert math'] = (ncert math, book.count(count ncert math)) #
d[menu_item] = (cost, order_count)
if book > 0:
d['ncert cs'] = (book, book.count(countbook)) # d[menu_item] = (cost,
order_count)
if water > 0
d_lst = sorted(d.items(), key=lambda x:x[1], reverse = True)
for item in d_lst:
print("Item: %s Cost: $%.2f OrderCount: %i "%(item[0], item[1][0], item[1]
[1]))

output:
ncert cs
ncert math
ncert eng

Q20. Write a Python program to update the Price of a


specific book in the Books table based on its BookID, and
display the updated record.
CODE:
mysql> INSERT INTO BOOKS VALUES
('L102', 'NCERT ENG', 19, 'XYZ', 2000),
('L103', 'NCERT MATH', 20, 'XYZ', 7000),
('L104', 'NCERT CS', 25, 'XYZ', 5000),
mysql> UPDATE BOOKS SET PRICE = PRICE + 100 WHERE BOOKID = ‘L104';
Query OK, 3 rows affected (0.06 sec)
Rows matched: 3 Changed: 3 Warnings: 0
OUTPUT:
mysql> select * from BOOKS;
+------------+-----------+------+------+--------+
| BOOKID | TITLE | AURTHOR| PRICE|
+------------+-----------+------+------+--------+
| L102 | NCERT ENG | XYZ | 2000 |
|L103 | NCERT MATH| XYZ |7000 |
| L104 | NCERT CS| XYZ | 5100 |
Q16.

ANSWERS
i. SELECT(ISSUEDATE)[(ISSUEDATE)]
FROM MEMBER
WHERE aggregate> 2016-01-01
ORDER BY issuedate DESC;
ii. SELECT(BNAME)

FROM BOOK
WHERE book type= Fiction,
iii. SELECT(TYPE,NO.OF BOOKS)
FROM BOOK
WHERE book type=comic,literature,fiction;

iv. SELECT( MNAME , ISSUEDATE )


FROM MEMBER
WHERE ISSUDATE>2017-01-01

v. M103 – S ARTHAK JOHN -F1 02

vi. F1 02- Untold Story- M103– S ARTHAK JOHN

vii. German easy

You might also like