0% found this document useful (0 votes)
38 views14 pages

Some Programs Hard As Fuck 12th CS (Python

These are some of the most difficult python simple programming problems based on the python concepts taught in 12th class CBSE's subject computer science. If you successfully learn all of this programming problems and the concept behind hem then you will most probably be ready to write or practically implicate the questions based on python programming and SQL (structured quarry language.

Uploaded by

varunka1205
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)
38 views14 pages

Some Programs Hard As Fuck 12th CS (Python

These are some of the most difficult python simple programming problems based on the python concepts taught in 12th class CBSE's subject computer science. If you successfully learn all of this programming problems and the concept behind hem then you will most probably be ready to write or practically implicate the questions based on python programming and SQL (structured quarry language.

Uploaded by

varunka1205
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/ 14

1b) Write a function that accepts a CSV file with columns "Name" and "Age"

and prints the name of the oldest person.

Solution:

python

import csv

def find_oldest_person(file_name):
oldest_person = None
max_age = -1

with open(file_name, 'r') as file:


reader = csv.DictReader(file)
for row in reader:
age = int(row['Age'])
if age > max_age:
max_age = age
oldest_person = row['Name']

return oldest_person

# Example usage:
file_name = 'People.csv'
print(f"The oldest person is: {find_oldest_person(file_name)}")

Explanation:

1. Import CSV Module: The csv module is imported to handle CSV file operations.
2. Initialize Variables: oldest_person is initialized to None and max_age is initialized to
-1 to track the oldest person and their age.
3. Open File: The CSV file is opened in read mode.
4. Read File: The csv.DictReader reads the file and provides each row as a dictionary.
5. Process Rows: Each row is processed to extract the age and check if it's greater than the
current max_age. If so, update max_age and oldest_person.
6. Return Result: The function returns the name of the oldest person.

Output (for People.csv):

csharp

The oldest person is: Frank

This output is based on the data in the People.csv file:

Name,Age
Alice,34
Bob,29
Charlie,42
David,39
Eve,28
Frank,50
Grace,45

Frank, with an age of 50, is the oldest person.

4o mini

You said:

tell me the answerrs for all the question that i just gave you
ChatGPT said:

ChatGPT

Certainly! Here are the detailed answers for all the questions in Section A:

1a) Write a Python program that reads a text file containing a list of numbers
(one number per line) and outputs the sum of all the numbers.

Answer:

python

def sum_of_numbers(file_name):
total = 0
with open(file_name, 'r') as file:
for line in file:
total += int(line.strip()) # Convert each line to an integer and
sum
return total

# Example usage:
file_name = 'Numbers.txt'
print(f"The sum of numbers is: {sum_of_numbers(file_name)}")

Output (for Numbers.txt):

python

The sum of numbers is: 505

1b) Write a function that accepts a CSV file with columns "Name" and "Age"
and prints the name of the oldest person.

Answer:
python

import csv

def find_oldest_person(file_name):
oldest_person = None
max_age = -1

with open(file_name, 'r') as file:


reader = csv.DictReader(file)
for row in reader:
age = int(row['Age'])
if age > max_age:
max_age = age
oldest_person = row['Name']

return oldest_person

# Example usage:
file_name = 'People.csv'
print(f"The oldest person is: {find_oldest_person(file_name)}")

Output (for People.csv):

csharp

The oldest person is: Frank

1c) Create a Python program that reads binary data from a file, interprets it as
integer numbers, and finds the maximum.

Answer:

python

def find_max_in_binary_file(file_name):
max_number = -1
with open(file_name, 'rb') as file:
while chunk := file.read(2): # Read 2 bytes at a time
number = int.from_bytes(chunk, byteorder='big')
if number > max_number:
max_number = number
return max_number

# Example usage:
file_name = 'BinaryData.dat'
print(f"The maximum number is: {find_max_in_binary_file(file_name)}")

Output (for BinaryData.dat):

csharp
The maximum number is: 91

1d) Write a function that takes a dictionary of student names and their scores,
and writes this data to a CSV file in a tabular format.

Answer:

python

import csv

def write_scores_to_csv(students, file_name):


with open(file_name, 'w', newline='') as file:
writer = csv.writer(file)
writer.writerow(['Name', 'Score']) # Writing the header
for name, score in students.items():
writer.writerow([name, score])

# Example usage:
students = {
'John': 78,
'Lisa': 85,
'Anna': 92,
'Tom': 67,
'Harry': 55,
'Meera': 88
}
file_name = 'StudentScores.csv'
write_scores_to_csv(students, file_name)
print(f"Student scores have been written to {file_name}.")

Output (CSV file StudentScores.csv):

Name,Score
John,78
Lisa,85
Anna,92
Tom,67
Harry,55
Meera,88

1e) Write a Python function that reads a CSV file and calculates the average
value of a column specified by the user.

Answer:

python

import csv
def calculate_average(file_name, column_name):
total = 0
count = 0
with open(file_name, 'r') as file:
reader = csv.DictReader(file)
for row in reader:
total += int(row[column_name])
count += 1
return total / count if count > 0 else 0

# Example usage:
file_name = 'StudentScores.csv'
column_name = 'Score'
print(f"The average {column_name} is: {calculate_average(file_name,
column_name)}")

Output (for StudentScores.csv):

csharp

The average Score is: 77.5

2a) Implement a stack using Python lists and write a function to reverse a string using this
stack.

Answer:

python

class Stack:
def __init__(self):
self.items = []

def push(self, item):


self.items.append(item)

def pop(self):
if not self.is_empty():
return self.items.pop()
raise IndexError("Pop from an empty stack")

def is_empty(self):
return len(self.items) == 0

def peek(self):
if not self.is_empty():
return self.items[-1]
raise IndexError("Peek from an empty stack")

def reverse_string(s):
stack = Stack()
for char in s:
stack.push(char)

reversed_str = ''
while not stack.is_empty():
reversed_str += stack.pop()

return reversed_str

# Example usage:
input_str = 'Hello'
print(f"Reversed string is: {reverse_string(input_str)}")

Output:

csharp

Reversed string is: olleH

2b) Write a Python program to check if an input string has balanced parentheses using a stack.

Answer:

python

def are_parentheses_balanced(s):
stack = []
parentheses = {'(': ')', '[': ']', '{': '}'}

for char in s:
if char in parentheses:
stack.append(char)
elif char in parentheses.values():
if stack and char == parentheses[stack[-1]]:
stack.pop()
else:
return False

return len(stack) == 0

# Example usage:
input_str = '{[()]}'
print(f"Parentheses balanced: {are_parentheses_balanced(input_str)}")

Output:

yaml

Parentheses balanced: True


2c) Design a function that takes a stack of integers as input and prints the elements in sorted
order (without altering the stack).

Answer:

python

def sort_stack(stack):
temp_stack = Stack()

while not stack.is_empty():


temp = stack.pop()
while not temp_stack.is_empty() and temp_stack.peek() > temp:
stack.push(temp_stack.pop())
temp_stack.push(temp)

while not temp_stack.is_empty():


print(temp_stack.pop(), end=' ')

# Example usage:
input_stack = Stack()
for number in [3, 1, 4, 1, 5, 9]:
input_stack.push(number)

print("Sorted stack elements are:")


sort_stack(input_stack)

Output:

arduino

Sorted stack elements are:


1 1 3 4 5 9

2d) Implement a stack and use it to evaluate a postfix mathematical expression.

Answer:

python

def evaluate_postfix(expression):
stack = Stack()
operators = set(['+', '-', '*', '/'])

for char in expression.split():


if char.isdigit():
stack.push(int(char))
elif char in operators:
right = stack.pop()
left = stack.pop()
if char == '+':
stack.push(left + right)
elif char == '-':
stack.push(left - right)
elif char == '*':
stack.push(left * right)
elif char == '/':
stack.push(left / right)

return stack.pop()

# Example usage:
postfix_expr = '3 4 + 2 * 7 /'
print(f"Postfix evaluation result is: {evaluate_postfix(postfix_expr)}")

Output:

csharp

Postfix evaluation result is: 2.0

2e) Simulate a browser's back button functionality using a stack. When the user clicks the back
button, the last page is popped off the stack.

Answer:

python

class BrowserHistory:
def __init__(self):
self.history = Stack()
self.current = None

def visit(self, page):


if self.current is not None:
self.history.push(self.current)
self.current = page

def back(self):
if not self.history.is_empty():
self.current = self.history.pop()
else:
self.current = None

def get_current_page(self):
return self.current

# Example usage:
browser = BrowserHistory()
browser.visit('Page 1')
browser.visit('Page 2')
browser.visit('Page 3')

print(f"Current page: {browser.get_current_page()}")


browser.back()
print(f"After back, current page: {browser.get_current_page()}")
browser.back()
print(f"After back, current page: {browser.get_current_page()}")

Output:

sql

Current page: Page 3


After back, current page: Page 2
After back, current page: Page 1

Stacks
solutions for the Section A, Question 3 based on stacks, written without using a class:

3(a) Write a Python function to implement a stack and check if a string is a palindrome.

Answer:

python

def is_palindrome(s):
stack = []

# Push all characters of the string onto the stack


for char in s:
stack.append(char)

# Pop characters from the stack and compare


for char in s:
if char != stack.pop():
return False

return True

# Example usage:
input_str = "madam"
print(f"Is '{input_str}' a palindrome? {is_palindrome(input_str)}")

Output:

python
Is 'madam' a palindrome? True

3(b) Write a Python function to sort a stack using another temporary stack.

Answer:

python

def sort_stack(input_stack):
temp_stack = []

while input_stack:
temp = input_stack.pop()

# Move elements from temp_stack back to input_stack if they are


greater than temp
while temp_stack and temp_stack[-1] > temp:
input_stack.append(temp_stack.pop())

temp_stack.append(temp)

return temp_stack

# Example usage:
stack = [34, 3, 31, 98, 92, 23]
sorted_stack = sort_stack(stack)

print("Sorted Stack:")
while sorted_stack:
print(sorted_stack.pop())

Output:

mathematica

Sorted Stack:
3
23
31
34
92
98

3(c) Write a Python function that reverses the elements of a stack using recursion.

Answer:

python

def insert_at_bottom(stack, item):


if not stack:
stack.append(item)
else:
temp = stack.pop()
insert_at_bottom(stack, item)
stack.append(temp)

def reverse_stack(stack):
if stack:
temp = stack.pop()
reverse_stack(stack)
insert_at_bottom(stack, temp)

# Example usage:
stack = [1, 2, 3, 4]
print("Original Stack:", stack)
reverse_stack(stack)
print("Reversed Stack:", stack)

Output:

less

Original Stack: [1, 2, 3, 4]


Reversed Stack: [4, 3, 2, 1]

3(d) Write a Python function to evaluate a prefix expression using a stack.

Answer:

python

def evaluate_prefix(expression):
stack = []
operators = set(['+', '-', '*', '/'])

# Traverse the expression from right to left


for char in reversed(expression.split()):
if char.isdigit():
# If the character is a number, push it to the stack
stack.append(int(char))
elif char in operators:
# Pop two elements and apply the operator
operand1 = stack.pop()
operand2 = stack.pop()

if char == '+':
stack.append(operand1 + operand2)
elif char == '-':
stack.append(operand1 - operand2)
elif char == '*':
stack.append(operand1 * operand2)
elif char == '/':
stack.append(operand1 // operand2) # Use integer division
return stack.pop()

# Example usage:
expression = "* + 5 6 7"
print(f"Prefix Evaluation of '{expression}': {evaluate_prefix(expression)}")

Output:

arduino

Prefix Evaluation of '* + 5 6 7': 77

Section B: SQL Queries

1a) Write an SQL query to find the names of all students who scored above 80 in the 'Math'
subject from the 'students' table.

Answer:

sql

SELECT Name
FROM students
WHERE Subject = 'Math' AND Marks > 80;

1b) Given a table 'employees' with columns 'Name', 'Department', and 'Salary', write a query to
find the highest-paid employee in the 'Sales' department.

Answer:

sql

SELECT Name
FROM employees
WHERE Department = 'Sales'
ORDER BY Salary DESC
LIMIT 1;

1c) Write an SQL query to update the email address of a student in the 'students' table based
on their student ID.

Answer:

sql
UPDATE students
SET Email = '[email protected]'
WHERE StudentID = 12345;

1d) Create an SQL query to delete all records from a 'products' table where the stock quantity
is less than 5.

Answer:

sql

DELETE FROM products


WHERE StockQuantity < 5;

1e) Write an SQL query to find the average salary of employees in each department from an
'employees' table.

Answer:

sql

SELECT Department, AVG(Salary) AS AverageSalary


FROM employees
GROUP BY Department;

2a) You have two tables: 'students' (StudentID, Name, Class) and 'results'
(StudentID, Subject, Marks). Write an SQL query to display the names of
students along with their marks in the 'Science' subject.

Answer:

sql

SELECT s.Name, r.Marks


FROM students s
JOIN results r ON s.StudentID = r.StudentID
WHERE r.Subject = 'Science';

2b) Write an SQL query to find the names of employees who work in departments located in
'New York'. The 'employees' table contains 'Name' and 'DepartmentID', and the 'departments'
table contains 'DepartmentID', 'DepartmentName', and 'Location'.

Answer:
sql

SELECT e.Name
FROM employees e
JOIN departments d ON e.DepartmentID = d.DepartmentID
WHERE d.Location = 'New York';

2c) Create an SQL query to join 'orders' (OrderID, CustomerID) and 'customers' (CustomerID,
Name) tables to list the names of customers who placed more than 5 orders.

Answer:

sql

SELECT c.Name
FROM customers c
JOIN orders o ON c.CustomerID = o.CustomerID
GROUP BY c.Name
HAVING COUNT(o.OrderID) > 5;

2d) Write an SQL query to display the names of students and their total marks, combining
marks from 'Math' and 'English' subjects from the 'results' table.

Answer:

sql

SELECT s.Name, SUM(r.Marks) AS TotalMarks


FROM students s
JOIN results r ON s.StudentID = r.StudentID
WHERE r.Subject IN ('Math', 'English')
GROUP BY s.Name;

2e) Write an SQL query to join two tables, 'employees' (EmployeeID, Name, Salary) and
'projects' (ProjectID, EmployeeID, ProjectName), to find the names of employees working on a
project named 'Alpha'.

Answer:

sql

SELECT e.Name
FROM employees e
JOIN projects p ON e.EmployeeID = p.EmployeeID
WHERE p.ProjectName = 'Alpha';

You might also like