Some Programs Hard As Fuck 12th CS (Python
Some Programs Hard As Fuck 12th CS (Python
Solution:
python
import csv
def find_oldest_person(file_name):
oldest_person = None
max_age = -1
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.
csharp
Name,Age
Alice,34
Bob,29
Charlie,42
David,39
Eve,28
Frank,50
Grace,45
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)}")
python
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
return oldest_person
# Example usage:
file_name = 'People.csv'
print(f"The oldest person is: {find_oldest_person(file_name)}")
csharp
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)}")
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
# 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}.")
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)}")
csharp
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 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
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
Answer:
python
def sort_stack(stack):
temp_stack = Stack()
# Example usage:
input_stack = Stack()
for number in [3, 1, 4, 1, 5, 9]:
input_stack.push(number)
Output:
arduino
Answer:
python
def evaluate_postfix(expression):
stack = Stack()
operators = set(['+', '-', '*', '/'])
return stack.pop()
# Example usage:
postfix_expr = '3 4 + 2 * 7 /'
print(f"Postfix evaluation result is: {evaluate_postfix(postfix_expr)}")
Output:
csharp
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 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')
Output:
sql
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 = []
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()
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 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
Answer:
python
def evaluate_prefix(expression):
stack = []
operators = set(['+', '-', '*', '/'])
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
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
1e) Write an SQL query to find the average salary of employees in each department from an
'employees' table.
Answer:
sql
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
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
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';