0% found this document useful (0 votes)
5 views21 pages

CS Practical File

This document is a practical file for a Class 12 student, Arsh Arora, detailing various Python programming problems and their solutions. It covers topics such as number operations, file handling, data analysis, SQL queries, and MySQL-Python connectivity. The file also includes a certificate of completion from the supervising teacher, Ms. Yashika Budhraja Malhotra.

Uploaded by

Arsh Arora
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)
5 views21 pages

CS Practical File

This document is a practical file for a Class 12 student, Arsh Arora, detailing various Python programming problems and their solutions. It covers topics such as number operations, file handling, data analysis, SQL queries, and MySQL-Python connectivity. The file also includes a certificate of completion from the supervising teacher, Ms. Yashika Budhraja Malhotra.

Uploaded by

Arsh Arora
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
You are on page 1/ 21

Prepared By

Arsh Arora
Class 12C
Roll No:
Amity International School,
Pushp Vihar

PYTHON
CS PRACTICAL FILE
TM
CERTIFICATE
This is to certify that
Arsh Arora of class
XII has completed the
practical questions
during the session of
2024-25 under my
guidance and
supervision

Ms. Yashika Budhraja Malhotra

Pg. 2
Problem 1: Number Operations
Write functions for:
1. Counting digits in a number.
2. Reversing a number.
3. Checking if a digit exists in a number.
4. Showing the number in expanded form.

Solution:

def count(n):
return len(str(n))
def reverse(n):
return int(str(n)[::-1])
def hasdigit(n, d):
return str(d) in str(n)
def show(n):
digits = list(str(n))
expanded = " + ".join(f"{digit}{'0' * (len(digits) - i -
1)}" for i, digit in enumerate(digits))
return expanded

# Example
num = 124
print(count(num)) # Output: 3
print(reverse(num)) # Output: 421
print(hasdigit(num, 2))# Output: True
print(show(num)) # Output: 100 + 20 + 4
Problem 2: Perfect and Prime
Numbers
Define functions to generate factors, check for
primes, and identify perfect numbers.

Solution:

def generate_factors(n):
return [i for i in range(1, n) if n % i == 0]
def is_prime_no(n):
if n < 2:
return False
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
return False
return True
def is_perfect_no(n):
return sum(generate_factors(n)) == n

# Example
num = 28
print(generate_factors(num))# Output: [1, 2, 4, 7, 14]
print(is_prime_no(num))# Output: False
print(is_perfect_no(num))# Output: True
Problem 3: Roman to Integer
Conversion
Convert Roman numerals to integers.

Solution:

def roman_to_int(s):
roman = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D':
500, 'M': 1000}
total = 0
prev_value = 0
for char in reversed(s):
value = roman[char]
if value < prev_value:
total -= value
else:
total += value
prev_value = value
return total

# Example
print(roman_to_int('LVIII'))# Output: 58
print(roman_to_int('MCMXCIV')) # Output: 1994
Problem 4: Number Conversion
Convert a decimal number to binary, octal, or
hexadecimal without using built-in functions.

Solution:

def decimal_to_other(n, base):


digits = "0123456789ABCDEF"
result = ""
while n > 0:
result = digits[n % base] + result
n //= base
return result

# Example
print(decimal_to_other(12, 2)) # Binary Output:
1100
print(decimal_to_other(12, 8)) # Octal Output: 14
print(decimal_to_other(12, 16)) # Hexadecimal
Output: C
Problem 5: Matrix Reshaping
Reshape a matrix if possible.

Solution:

def reshape(mat, r, c):


flat = [num for row in mat for num in row]
if len(flat) != r * c:
return mat
return [flat[i * c:(i + 1) * c] for i in range(r)]

# Example
matrix = [[1, 2], [3, 4]]
print(reshape(matrix, 1, 4))# Output: [[1, 2, 3, 4]]
print(reshape(matrix, 2, 2))# Output: [[1, 2], [3, 4]]
Problem 6: File Handling
1. Read back the entire file content using read( ) or
readlines( ) and display on the screen.
2. Append more text of your choice in the file and
display the content of file with line numbers
prefixed to line.
3. Display last line of file.
4. Display first line from 10th character onwards.
5. Read and display a line from the file. Ask user to
provide the line number to be read. f) Find the
frequency of words beginning with every letter.

Solution:

def create_file():
with open("file.txt", "w") as f:
f.write("""Neither apple nor pine are in pineapple.
Boxing rings are square.
Writers write, but fingers don’t fing. Overlook and
oversee are opposites.
A house can burn up as it burns down. An alarm
goes off by going on.""")

def read_file():
with open("file.txt", "r") as f:
print(f.read())
def append_and_display():
with open("file.txt", "a") as f:
f.write("\nAdding more content for testing.")
with open("file.txt", "r") as f:
for i, line in enumerate(f.readlines(), 1):
print(f"{i}: {line.strip()}")

def display_last_line():
with open("file.txt", "r") as f:
print(f.readlines()[-1])

def display_first_line_from_10th():
with open("file.txt", "r") as f:
print(f.readline()[9:])

def display_line_by_number(line_num):
with open("file.txt", "r") as f:
lines = f.readlines()
if 0 < line_num <= len(lines):
print(lines[line_num - 1].strip())
else:
print("Line number out of range.")

def frequency_of_words():
from collections import defaultdict
with open("file.txt", "r") as f:
text = f.read().split()
freq = defaultdict(int)
for word in text:
freq[word[0].lower()] += 1
for letter, count in freq.items():
print(f"Words beginning with {letter}: {count}")
Problem 7: Filter Words
Starting with Vowels
Read from file1.txt and create file2.txt without
words starting with vowels.

Solution:

def isvowel():
with open("file1.txt", "r") as f1, open("file2.txt",
"w") as f2:
words = f1.read().split()
filtered_words = [word for word in words if
word[0].lower() not in 'aeiou']
f2.write(" ".join(filtered_words))

# Example
with open("file1.txt", "w") as f:
f.write("Carry Umbrella and Overcoat When it
Rains")
isvowel()
with open("file2.txt", "r") as f:
print(f.read()) # Output: Carry When Rains
Problem 8: Student Data Analysis
Copy student data to a list of tuples, sort, and analyze.

Solution:
def analyze_students():
students = [
("Rajat", "Sen", 12345, 1, "CSEE"),
("Jagat", "Narain", 13467, 3, "CSEE"),
("Anu", "Sharma", 11756, 2, "Biology"),
("Sumita", "Trikha", 23451, 4, "Biology"),
("Sumder", "Kumra", 11234, 3, "MME"),
("Kanti", "Bhushan", 23211, 3, "CSEE"),
]
# Sort by registration number
sorted_students = sorted(students, key=lambda x:
x[2])
print("Sorted by Registration Number:")
for student in sorted_students:
print(student)
# Students with no of years less than 3
print("\nStudents with less than 3 years:")
for student in students:
if student[3] < 3:
print(student[0], student[1])
# Count students per department
from collections import Counter
departments = Counter(student[4] for student in
students)
print("\nNumber of students per department:")
for dept, count in departments.items():
print(f"{dept}: {count}")
Problem 9: Word Histogram
and Analysis
Create a histogram, analyze word statistics, and
map words by length.

Solution:
def word_histogram(file_name):
from collections import Counter, defaultdict
with open(file_name, "r") as f:
words = f.read().split()
histogram = Counter(words)
print("Total number of words:",
sum(histogram.values()))
print("Number of different words:", len(histogram))
print("Most common words:",
histogram.most_common(3))

# Map words by length


length_map = defaultdict(list)
for word in words:
length_map[len(word)].append(word)
print("\nWords grouped by length:",
dict(length_map))
print("\nLongest words:",
length_map[max(length_map)])
print("Words longer than 4:", [word for word in words
if len(word) > 4])

#Example
with open("myfile.txt", "w") as f:
f.write("Neither apple nor pine are in pineapple. Boxing
rings are square.")
word_histogram("myfile.txt")
Problem 10: Binary File
Operations with Pickle
Solution:

import pickle

def hotel_operations():
customers = [
{"roomno": 101, "name": "John", "duration": 1},
{"roomno": 102, "name": "Alice", "duration": 3},
{"roomno": 103, "name": "Bob", "duration": 2},
]
# Write to file
with open("hotel.dat", "wb") as f:
pickle.dump(customers, f)
# Read from file
with open("hotel.dat", "rb") as f:
loaded_customers = pickle.load(f)
print("All Customers:", loaded_customers)
# Count customers staying more than 2 days
print("Customers staying > 2 days:")
for customer in loaded_customers:
if customer["duration"] > 2:
print(customer)
Problem 11: Placement Data
Analysis (CSV Handling)
Solution:
import csv
def placement_analysis():
# Read and print data
with open("placement.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerow(["SNO", "NAME", "MARKS1", "MARKS2",
"MARKS3", "MARKS4", "MARKS5"])
writer.writerow([1, "JOHN", 4, 3, 4, 2, 5])
writer.writerow([2, "PETER", 3, 4, 4, 3, 5])
with open("placement.csv", "r") as f:
reader = csv.reader(f)
for row in reader:
print(row)
# Count total people
with open("placement.csv", "r") as f:
reader = csv.reader(f)
next(reader) # Skip header
print("Total people:", sum(1 for _ in reader))
# Find top N by total marks
def top_n_students(n):
with open("placement.csv", "r") as f:
reader = csv.reader(f)
next(reader)
students = [
(row[1], sum(map(int, row[2:]))) for row in reader
]
top_students = sorted(students, key=lambda x: x[1],
reverse=True)[:n]
print("Top", n, "students:", top_students)

top_n_students(1)
Problem 12: Simulate a Ring
Game (Stack Implementation)
Solution:

def ring_game():
stack = []
temp_stack = []
while True:
ring = int(input("Enter ring diameter (0 to stop):
"))
if ring == 0:
break
while stack and stack[-1] <= ring:
temp_stack.append(stack.pop())
stack.append(ring)
while temp_stack:
stack.append(temp_stack.pop())
print("Final stack arrangement:", stack)
Problem 13: Backspace
Handling with Stacks
Solution:

def are_equal(str1, str2):


def process_string(s):
stack = []
for char in s:
if char == "#":
if stack:
stack.pop()
else:
stack.append(char)
return "".join(stack)

return process_string(str1) == process_string(str2)

# Example
print(are_equal("ab#c", "ad#c")) # Output: True
print(are_equal("ab##", "c#d#")) # Output: True
print(are_equal("a#c", "b")) # Output: False
Problem 14: SQL Query
Writing
This involves MySQL commands for operations on
tables like Tutor, WATCHES, and SALES.

Solution:

(1) Commands for Tutor Table

(i) Display names in descending order of those


whose age is not between 35 and 40
SELECT NAME FROM Tutor WHERE AGE NOT
BETWEEN 35 AND 40 ORDER BY NAME DESC;
(ii) List cities with their average fee
SELECT CITY, AVG(FEE) AS AvgFee FROM Tutor
GROUP BY CITY;
(iii) Decrease Shikha's fee by 5%
UPDATE Tutor SET FEE = FEE * 0.95 WHERE NAME =
'SHIKHA';
(iv) Cities with max and min fees
SELECT CITY FROM Tutor WHERE FEE = (SELECT
MAX(FEE) FROM Tutor);
SELECT CITY FROM Tutor WHERE FEE = (SELECT
MIN(FEE) FROM Tutor);
(v) Tutor names and cities living in a city with 'O' but
not 'P'
SELECT NAME, CITY FROM Tutor WHERE CITY LIKE
'%O%' AND CITY NOT LIKE '%P%';
Problem 14: SQL Query
Writing
This involves MySQL commands for operations on
tables like Tutor, WATCHES, and SALES.

Solution:

(2) Commands for Watches and Sales Tables

(i) Display watch names and quantities sold in Q1


SELECT WATCHES.Watch_Name, SALES.Qty_Sold
FROM WATCHES
JOIN SALES ON WATCHES.WatchId =
SALES.WatchId WHERE SALES.Quarter = 1;
(ii) Details of watches ending with "Time"
SELECT * FROM WATCHES WHERE Watch_Name
LIKE '%Time';
(iii) Total quantity in store of Unisex watches
SELECT SUM(Qty_Store) AS TotalQuantity FROM
WATCHES WHERE Type = 'Unisex';
(iv) Watches in the price range of 5000 to 15000
SELECT Watch_Name, Price FROM WATCHES
WHERE Price BETWEEN 5000 AND 15000;
(v) Quantity sold WatchId-wise
SELECT WatchId, SUM(Qty_Sold) AS TotalSold
FROM SALES GROUP BY WatchId;
Problem 15: MySQL-Python
Connectivity
Here’s Python code for interacting with the ITEM
table in MySQL:

Solution:

import mysql.connector

def item_operations():
conn = mysql.connector.connect(
host="localhost", user="root",
password="password", database="mydb"
)
cursor = conn.cursor()

# Create table
cursor.execute("""
CREATE TABLE IF NOT EXISTS ITEM (
Itemcode VARCHAR(10) PRIMARY KEY,
Itemname VARCHAR(50),
Price FLOAT
)
""")
# Insert records
def insert_item(itemcode, itemname, price):
cursor.execute("INSERT INTO ITEM (Itemcode,
Itemname, Price) VALUES (%s, %s, %s)",
(itemcode, itemname, price))
conn.commit()

# Display records
def display_items():
cursor.execute("SELECT * FROM ITEM")
for row in cursor.fetchall():
print(row)

# Search by Itemcode
def search_item(itemcode):
cursor.execute("SELECT * FROM ITEM WHERE
Itemcode = %s", (itemcode,))
print(cursor.fetchone())

# Example Operations
insert_item("I001", "Notebook", 50)
insert_item("I002", "Pen", 10)
display_items()
search_item("I001")

conn.close()

# Example
item_operations()
Arsh Arora
XII-C
THANK YOU!
Amity International
School, Pushp Vihar

Contact Me:
[email protected]
+91 9650233290
linkedin.com/in/arsharora2112

You might also like