Assignment 3 Lassi
Assignment 3 Lassi
Python Code:
import math
def calculator():
while True:
print("\n--- Simple Calculator ---")
print("Operations: add, subtract, multiply, divide,
sin, cos, tan, exit")
choice = input("Enter operation: ").lower()
match choice:
case 'add':
a = float(input("Enter first number: "))
b = float(input("Enter second number: "))
print(f"Result: {a + b}")
case 'subtract':
a = float(input("Enter first number: "))
b = float(input("Enter second number: "))
print(f"Result: {a - b}")
case 'multiply':
a = float(input("Enter first number: "))
b = float(input("Enter second number: "))
print(f"Result: {a * b}")
case 'divide':
try:
a = float(input("Enter numerator: "))
b = float(input("Enter denominator: "))
result = a / b
print(f"Result: {result}")
except ZeroDivisionError:
print("Error: Cannot divide by zero.")
case 'sin':
angle = float(input("Enter angle in degrees:
"))
print(f"sin({angle}) =
{math.sin(math.radians(angle))}")
case 'cos':
angle = float(input("Enter angle in degrees:
"))
print(f"cos({angle}) =
{math.cos(math.radians(angle))}")
case 'tan':
angle = float(input("Enter angle in degrees:
"))
print(f"tan({angle}) =
{math.tan(math.radians(angle))}")
case 'exit':
print("Exiting calculator.")
break
case _:
print("Invalid operation. Try again.")
calculator()
OUTPUT:
QUESTION: 2
Design and implement a Python program to manage student information using lambda
functions. The data should include 08 students (4 boys + 4 girls) from Section C, stored
across 4 dictionaries: Name, Roll Number, City (use four different city names), and
Marks. The program should provide a menu-driven interface that allows the user to:
- Sort students by marks
- Sort students alphabetically by name
- Filter students based on city
- Filter students based on Gender
- Exit the program
Python Code:
students = {
"Name": ["Ankit", "Riya", "Mohit", "Tanya", "Rahul",
"Sneha", "Aman", "Priya"],
"Roll": [101, 102, 103, 104, 105, 106, 107, 108],
"City": ["Delhi", "Mumbai", "Chennai", "Kolkata", "Delhi",
"Mumbai", "Chennai", "Kolkata"],
"Marks": [82, 91, 76, 85, 67, 89, 74, 95],
"Gender": ["Male", "Female", "Male", "Female", "Male",
"Female", "Male", "Female"]
}
def display_students(filtered_indices):
print("\n{:<10} {:<5} {:<10} {:<5} {:<6}".format("Name",
"Roll", "City", "Marks", "Gender"))
for i in filtered_indices:
print("{:<10} {:<5} {:<10} {:<5} {:<6}".format(
students["Name"][i], students["Roll"][i],
students["City"][i], students["Marks"][i],
students["Gender"][i]))
while True:
print("\nMenu:")
print("1. Sort by Marks")
print("2. Sort by Name")
print("3. Filter by City")
print("4. Filter by Gender")
print("5. Exit")
choice = input("Enter your choice: ")
if choice == '1':
sorted_idx = sorted(range(len(students["Marks"])),
key=lambda x: students["Marks"][x])
display_students(sorted_idx)
elif choice == '2':
sorted_idx = sorted(range(len(students["Name"])),
key=lambda x: students["Name"][x])
display_students(sorted_idx)
elif choice == '3':
city = input("Enter city to filter: ")
filtered = [i for i, c in enumerate(students["City"])
if c.lower() == city.lower()]
display_students(filtered)
elif choice == '4':
gender = input("Enter gender to filter (Male/Female):
")
filtered = [i for i, g in
enumerate(students["Gender"]) if g.lower() == gender.lower()]
display_students(filtered)
elif choice == '5':
print("Exiting...")
break
else:
print("Invalid input. Try again.")
OUTPUT:
QUESTION:3
Create and display a Pandas DataFrame using the student data provided in Question 2.
Python Code:
import pandas as pd
student_data = {
"Name": ["Ankit", "Riya", "Mohit", "Tanya", "Rahul",
"Sneha", "Aman", "Priya"],
"Roll Number": [101, 102, 103, 104, 105, 106, 107, 108],
"City": ["Delhi", "Mumbai", "Chennai", "Kolkata", "Delhi",
"Mumbai", "Chennai", "Kolkata"],
"Marks": [82, 91, 76, 85, 67, 89, 74, 95],
"Gender": ["Male", "Female", "Male", "Female", "Male",
"Female", "Male", "Female"]
}
df = pd.DataFrame(student_data)
OUTPUT:
QUESTION:4
Develop a Python program that uses NumPy structured arrays to manage and analyze
data for 06 Indian fruits. Each fruit should be represented by: Name and Price per Kg.
(Price range Rs 40 to Rs 150). The program must:
- Display all fruit records in a dataframe
- Calculate and display the average, highest, and lowest price per kilogram (NumPy
operation)
- Filter and display fruits with a price greater than ₹40 and less than 100 (NumPy
operation)
Python Code:
import numpy as np
import pandas as pd
fruit_data = np.array([
("Apple", 120),
("Banana", 45),
("Mango", 90),
("Grapes", 70),
("Papaya", 60),
("Pineapple", 130)
], dtype=[("Name", "U20"), ("Price", "i4")])
fruit_df = pd.DataFrame(fruit_data)
print("All Fruits:\n", fruit_df)
prices = fruit_data["Price"]
print("\nAverage Price:", np.mean(prices))
print("Highest Price:", np.max(prices))
print("Lowest Price:", np.min(prices))