← Computer Programming II

Variant 1: Warehouse Inventory Tracker

You are building an inventory system for a warehouse. Create a Product dataclass and a Warehouse dataclass that manages products, tracks stock levels, and supports restocking and sales.

  1. Import dataclass and field from the dataclasses module.
  2. Create a Product dataclass with fields: name (str), price (float), and quantity (int).
  3. Add a method value(self) -> float that returns price * quantity.
  4. Create a Warehouse dataclass with fields: name (str), products (list of Product, empty by default), and a computed field total_value (float) that is not a constructor parameter. total_value must be computed in __post_init__ as the sum of every product’s value, and must stay accurate after every operation.
  5. Add a method add_product(self, product: Product) that adds the product to the list and updates total_value.
  6. Add a method sell(self, product_name: str, qty: int) -> bool that finds the product by name, reduces its quantity by qty only if enough stock exists, updates total_value, and returns whether the sale succeeded.
  7. Add a method restock(self, product_name: str, qty: int) that finds the product by name and increases its quantity by qty, then updates total_value.
  8. Add a method report(self) -> str that returns a formatted summary. Study the expected output to determine the exact format.

Input

p1 = Product("Laptop", 999.99, 10)
p2 = Product("Mouse", 29.99, 50)
p3 = Product("Keyboard", 79.99, 30)

w = Warehouse("TechDepot")
w.add_product(p1)
w.add_product(p2)
w.add_product(p3)

print(w.total_value)
print(w.sell("Laptop", 3))
print(w.sell("Laptop", 20))
w.restock("Mouse", 25)
print(w.report())

Expected Output

13899.1
True
False
TechDepot Inventory:
  Laptop: 7 units @ $999.99 each
  Mouse: 75 units @ $29.99 each
  Keyboard: 30 units @ $79.99 each
Total value: $11648.88

Variant 2: Fitness Class Manager

You run a fitness studio and need to track classes, enrollments, and member performance. Create a Member dataclass and a FitnessClass dataclass that manages enrollment, attendance scoring, and member comparison.

  1. Import dataclass and field from the dataclasses module.
  2. Create a Member dataclass with fields: name (str), member_id (str), sessions_attended (int, default 0), and calories_burned (list of int, empty by default).
  3. Add a method log_session(self, calories: int) that increments sessions_attended by 1 and appends the calories to the list.
  4. Add a method avg_calories(self) -> float that returns the average calories burned per session, or 0.0 if no sessions have been logged.
  5. Create a FitnessClass dataclass with fields: class_name (str), instructor (str), capacity (int), members (list of Member, empty by default), and a computed field enrolled (int) that is not a constructor parameter. enrolled must reflect the current number of members and stay accurate after every operation.
  6. Add a method enroll(self, member: Member) -> bool that adds the member only if the class is not full. Returns whether enrollment succeeded.
  7. Add a method best_performer(self) -> str that returns the name of the member with the highest average calories burned. If there are no members or all averages are zero, return "No data".
  8. Add a method class_stats(self) -> str that returns a formatted summary. Study the expected output to determine the exact format.

Input

m1 = Member("Alice", "M001")
m2 = Member("Bob", "M002")
m3 = Member("Charlie", "M003")

m1.log_session(350)
m1.log_session(420)
m1.log_session(380)
m2.log_session(500)
m2.log_session(450)
m3.log_session(300)

fc = FitnessClass("HIIT", "Coach Dana", 3)
print(fc.enroll(m1))
print(fc.enroll(m2))
print(fc.enroll(m3))
print(fc.enroll(Member("Dave", "M004")))
print(fc.enrolled)
print(fc.best_performer())
print(fc.class_stats())

Expected Output

True
True
True
False
3
Bob
HIIT (Coach Dana):
  Alice - 3 sessions, avg 383.3 cal
  Bob - 2 sessions, avg 475.0 cal
  Charlie - 1 sessions, avg 300.0 cal
Enrolled: 3/3

Variant 3: Recipe Book

You are building a recipe management app. Create an Ingredient dataclass and a Recipe dataclass that handles ingredient management, nutritional calculations, and scaling.

  1. Import dataclass and field from the dataclasses module.
  2. Create an Ingredient dataclass with fields: name (str), grams (float), and calories_per_gram (float).
  3. Add a method total_calories(self) -> float that returns grams * calories_per_gram.
  4. Create a Recipe dataclass with fields: title (str), servings (int), ingredients (list of Ingredient, empty by default), and a computed field total_calories (float) that is not a constructor parameter. total_calories must be computed in __post_init__ as the sum of every ingredient’s calories, and must stay accurate after every operation.
  5. Add a method add_ingredient(self, ingredient: Ingredient) that adds the ingredient and updates total_calories.
  6. Add a method calories_per_serving(self) -> float that returns total_calories / servings.
  7. Add a method scale(self, new_servings: int) that adjusts every ingredient’s grams proportionally to the new serving count, updates servings, and recalculates total_calories.
  8. Add a method display(self) -> str that returns a formatted summary. Study the expected output to determine the exact format.

Input

r = Recipe("Pancakes", 4)
r.add_ingredient(Ingredient("Flour", 200.0, 3.64))
r.add_ingredient(Ingredient("Milk", 300.0, 0.42))
r.add_ingredient(Ingredient("Egg", 100.0, 1.55))

print(r.total_calories)
print(r.calories_per_serving())
print(r.display())

r.scale(2)
print(r.display())

Expected Output

1009.0
252.25
Pancakes (4 servings):
  Flour: 200.0g (728.0 cal)
  Milk: 300.0g (126.0 cal)
  Egg: 100.0g (155.0 cal)
Per serving: 252.25 cal

Pancakes (2 servings):
  Flour: 100.0g (364.0 cal)
  Milk: 150.0g (63.0 cal)
  Egg: 50.0g (77.5 cal)
Per serving: 252.25 cal

Variant 4: Restaurant Menu Tracker

You are building a management system for a restaurant. Create a MenuItem dataclass and a Restaurant dataclass that manages menu items, tracks servings, and supports resupply and serving customers.

  1. Import dataclass and field from the dataclasses module.
  2. Create a MenuItem dataclass with fields: name (str), price (float), and quantity (int).
  3. Add a method value(self) -> float that returns round(price * quantity, 2).
  4. Create a Restaurant dataclass with fields: name (str), menu_items (list of MenuItem, empty by default), and a computed field total_revenue (float) that is not a constructor parameter. total_revenue must be computed in __post_init__ as the rounded sum of every item’s value, and must stay accurate after every operation.
  5. Add a method add_item(self, item: MenuItem) that adds the item to the list and updates total_revenue.
  6. Add a method serve(self, item_name: str, qty: int) -> bool that finds the item by name, reduces its quantity by qty only if enough servings exist, updates total_revenue, and returns whether the serve succeeded.
  7. Add a method resupply(self, item_name: str, qty: int) that finds the item by name and increases its quantity by qty, then updates total_revenue.
  8. Add a method report(self) -> str that returns a formatted summary. Study the expected output to determine the exact format.

Input

m1 = MenuItem("Burger", 12.99, 20)
m2 = MenuItem("Salad", 8.49, 40)
m3 = MenuItem("Pasta", 14.99, 15)

r = Restaurant("BistroHub")
r.add_item(m1)
r.add_item(m2)
r.add_item(m3)

print(r.total_revenue)
print(r.serve("Burger", 5))
print(r.serve("Burger", 25))
r.resupply("Salad", 10)
print(r.report())

Expected Output

824.25
True
False
BistroHub Menu:
  Burger: 15 servings @ $12.99 each
  Salad: 50 servings @ $8.49 each
  Pasta: 15 servings @ $14.99 each
Total revenue: $844.2

Variant 5: Course Enrollment System

You manage a university enrollment system and need to track courses, student registrations, and academic performance. Create a Student dataclass and a Course dataclass that manages enrollment, grade tracking, and student comparison.

  1. Import dataclass and field from the dataclasses module.
  2. Create a Student dataclass with fields: name (str), student_id (str), assignments_done (int, default 0), and scores (list of int, empty by default).
  3. Add a method submit(self, score: int) that increments assignments_done by 1 and appends the score to the list.
  4. Add a method avg_score(self) -> float that returns the average score across all submissions, or 0.0 if no assignments have been submitted.
  5. Create a Course dataclass with fields: course_name (str), professor (str), capacity (int), students (list of Student, empty by default), and a computed field enrolled (int) that is not a constructor parameter. enrolled must reflect the current number of students and stay accurate after every operation.
  6. Add a method enroll(self, student: Student) -> bool that adds the student only if the course is not full. Returns whether enrollment succeeded.
  7. Add a method top_student(self) -> str that returns the name of the student with the highest average score. If there are no students or all averages are zero, return "No data".
  8. Add a method course_stats(self) -> str that returns a formatted summary. Study the expected output to determine the exact format.

Input

s1 = Student("Liam", "S101")
s2 = Student("Nora", "S102")
s3 = Student("Omar", "S103")

s1.submit(72)
s1.submit(88)
s1.submit(91)
s2.submit(95)
s2.submit(89)
s3.submit(60)

c = Course("Data Structures", "Prof. Kim", 3)
print(c.enroll(s1))
print(c.enroll(s2))
print(c.enroll(s3))
print(c.enroll(Student("Priya", "S104")))
print(c.enrolled)
print(c.top_student())
print(c.course_stats())

Expected Output

True
True
True
False
3
Nora
Data Structures (Prof. Kim):
  Liam - 3 assignments, avg 83.7 pts
  Nora - 2 assignments, avg 92.0 pts
  Omar - 1 assignments, avg 60.0 pts
Enrolled: 3/3

Variant 6: Construction Project Planner

You are building a cost estimation tool for construction projects. Create a Material dataclass and a Project dataclass that handles material management, cost calculations, and scaling to different production volumes.

  1. Import dataclass and field from the dataclasses module.
  2. Create a Material dataclass with fields: name (str), kilograms (float), and cost_per_kg (float).
  3. Add a method total_cost(self) -> float that returns kilograms * cost_per_kg.
  4. Create a Project dataclass with fields: title (str), units (int), materials (list of Material, empty by default), and a computed field total_cost (float) that is not a constructor parameter. total_cost must be computed in __post_init__ as the sum of every material’s cost, and must stay accurate after every operation.
  5. Add a method add_material(self, material: Material) that adds the material and updates total_cost.
  6. Add a method cost_per_unit(self) -> float that returns total_cost / units.
  7. Add a method scale(self, new_units: int) that adjusts every material’s kilograms proportionally to the new unit count, updates units, and recalculates total_cost.
  8. Add a method display(self) -> str that returns a formatted summary. Study the expected output to determine the exact format.

Input

p = Project("Bookshelf", 10)
p.add_material(Material("Wood", 50.0, 8.0))
p.add_material(Material("Nails", 5.0, 3.5))
p.add_material(Material("Varnish", 10.0, 12.0))

print(p.total_cost)
print(p.cost_per_unit())
print(p.display())

p.scale(5)
print(p.display())

Expected Output

537.5
53.75
Bookshelf (10 units):
  Wood: 50.0kg ($400.0)
  Nails: 5.0kg ($17.5)
  Varnish: 10.0kg ($120.0)
Per unit: $53.75

Bookshelf (5 units):
  Wood: 25.0kg ($200.0)
  Nails: 2.5kg ($8.75)
  Varnish: 5.0kg ($60.0)
Per unit: $53.75

Variant 7: Bookstore Stock Manager

You are building a stock management system for a bookstore. Create a Book dataclass and a Bookstore dataclass that manages books, tracks stock levels, and supports restocking and sales.

  1. Import dataclass and field from the dataclasses module.
  2. Create a Book dataclass with fields: title (str), price (float), and copies (int).
  3. Add a method value(self) -> float that returns round(price * copies, 2).
  4. Create a Bookstore dataclass with fields: name (str), books (list of Book, empty by default), and a computed field total_stock_value (float) that is not a constructor parameter. total_stock_value must be computed in __post_init__ as the rounded sum of every book’s value, and must stay accurate after every operation.
  5. Add a method add_book(self, book: Book) that adds the book to the list and updates total_stock_value.
  6. Add a method sell(self, title: str, qty: int) -> bool that finds the book by title, reduces its copies by qty only if enough stock exists, updates total_stock_value, and returns whether the sale succeeded.
  7. Add a method restock(self, title: str, qty: int) that finds the book by title and increases its copies by qty, then updates total_stock_value.
  8. Add a method report(self) -> str that returns a formatted summary. Study the expected output to determine the exact format.

Input

b1 = Book("Python Basics", 34.99, 25)
b2 = Book("Data Science", 49.99, 15)
b3 = Book("Web Dev", 27.50, 40)

s = Bookstore("PageTurn")
s.add_book(b1)
s.add_book(b2)
s.add_book(b3)

print(s.total_stock_value)
print(s.sell("Python Basics", 10))
print(s.sell("Python Basics", 20))
s.restock("Web Dev", 20)
print(s.report())

Expected Output

2724.6
True
False
PageTurn Catalog:
  Python Basics: 15 copies @ $34.99 each
  Data Science: 15 copies @ $49.99 each
  Web Dev: 60 copies @ $27.5 each
Total stock value: $2924.7

Variant 8: Sports Team Roster

You manage a sports league and need to track teams, player registrations, and game performance. Create a Player dataclass and a Team dataclass that manages roster limits, stat tracking, and player comparison.

  1. Import dataclass and field from the dataclasses module.
  2. Create a Player dataclass with fields: name (str), player_id (str), games_played (int, default 0), and points (list of int, empty by default).
  3. Add a method record_game(self, pts: int) that increments games_played by 1 and appends the points to the list.
  4. Add a method avg_points(self) -> float that returns the average points per game, or 0.0 if no games have been played.
  5. Create a Team dataclass with fields: team_name (str), coach (str), max_roster (int), players (list of Player, empty by default), and a computed field roster_size (int) that is not a constructor parameter. roster_size must reflect the current number of players and stay accurate after every operation.
  6. Add a method sign(self, player: Player) -> bool that adds the player only if the roster is not full. Returns whether signing succeeded.
  7. Add a method mvp(self) -> str that returns the name of the player with the highest average points. If there are no players or all averages are zero, return "No data".
  8. Add a method team_stats(self) -> str that returns a formatted summary. Study the expected output to determine the exact format.

Input

p1 = Player("Alex", "P01")
p2 = Player("Jordan", "P02")
p3 = Player("Sam", "P03")

p1.record_game(18)
p1.record_game(24)
p1.record_game(21)
p2.record_game(30)
p2.record_game(27)
p3.record_game(12)

t = Team("Thunder", "Coach Rivers", 3)
print(t.sign(p1))
print(t.sign(p2))
print(t.sign(p3))
print(t.sign(Player("Taylor", "P04")))
print(t.roster_size)
print(t.mvp())
print(t.team_stats())

Expected Output

True
True
True
False
3
Jordan
Thunder (Coach Rivers):
  Alex - 3 games, avg 21.0 pts
  Jordan - 2 games, avg 28.5 pts
  Sam - 1 games, avg 12.0 pts
Roster: 3/3

Variant 9: Product Assembly Line

You are building a production planning tool for a factory. Create a Component dataclass and an Assembly dataclass that handles component management, cost calculations, and scaling to different batch sizes.

  1. Import dataclass and field from the dataclasses module.
  2. Create a Component dataclass with fields: name (str), units (float), and price_per_unit (float).
  3. Add a method total_price(self) -> float that returns units * price_per_unit.
  4. Create an Assembly dataclass with fields: title (str), batch_size (int), components (list of Component, empty by default), and a computed field total_price (float) that is not a constructor parameter. total_price must be computed in __post_init__ as the sum of every component’s price, and must stay accurate after every operation.
  5. Add a method add_component(self, component: Component) that adds the component and updates total_price.
  6. Add a method price_per_item(self) -> float that returns total_price / batch_size.
  7. Add a method scale(self, new_batch_size: int) that adjusts every component’s units proportionally to the new batch size, updates batch_size, and recalculates total_price.
  8. Add a method display(self) -> str that returns a formatted summary. Study the expected output to determine the exact format.

Input

a = Assembly("Drone", 8)
a.add_component(Component("Motor", 32.0, 15.0))
a.add_component(Component("Frame", 8.0, 45.0))
a.add_component(Component("Battery", 16.0, 25.0))

print(a.total_price)
print(a.price_per_item())
print(a.display())

a.scale(4)
print(a.display())

Expected Output

1240.0
155.0
Drone (8 items):
  Motor: 32.0 units ($480.0)
  Frame: 8.0 units ($360.0)
  Battery: 16.0 units ($400.0)
Per item: $155.0

Drone (4 items):
  Motor: 16.0 units ($240.0)
  Frame: 4.0 units ($180.0)
  Battery: 8.0 units ($200.0)
Per item: $155.0

Variant 10: Tool Rental Workshop

You are building a rental tracking system for a workshop. Create a Tool dataclass and a Workshop dataclass that manages tools, tracks rental hours, and supports usage and extensions.

  1. Import dataclass and field from the dataclasses module.
  2. Create a Tool dataclass with fields: name (str), rate (float), and hours (int).
  3. Add a method cost(self) -> float that returns round(rate * hours, 2).
  4. Create a Workshop dataclass with fields: name (str), tools (list of Tool, empty by default), and a computed field total_cost (float) that is not a constructor parameter. total_cost must be computed in __post_init__ as the rounded sum of every tool’s cost, and must stay accurate after every operation.
  5. Add a method add_tool(self, tool: Tool) that adds the tool to the list and updates total_cost.
  6. Add a method use(self, tool_name: str, hrs: int) -> bool that finds the tool by name, reduces its hours by hrs only if enough hours remain, updates total_cost, and returns whether the usage succeeded.
  7. Add a method extend(self, tool_name: str, hrs: int) that finds the tool by name and increases its hours by hrs, then updates total_cost.
  8. Add a method report(self) -> str that returns a formatted summary. Study the expected output to determine the exact format.

Input

t1 = Tool("Drill", 18.50, 12)
t2 = Tool("Saw", 25.99, 8)
t3 = Tool("Sander", 12.75, 20)

w = Workshop("BuildRight")
w.add_tool(t1)
w.add_tool(t2)
w.add_tool(t3)

print(w.total_cost)
print(w.use("Drill", 4))
print(w.use("Drill", 15))
w.extend("Sander", 10)
print(w.report())

Expected Output

684.92
True
False
BuildRight Rentals:
  Drill: 8 hrs @ $18.5/hr
  Saw: 8 hrs @ $25.99/hr
  Sander: 30 hrs @ $12.75/hr
Total cost: $738.42

Variant 11: Department Staffing System

You manage a company’s HR system and need to track departments, employee hiring, and performance ratings. Create an Employee dataclass and a Department dataclass that manages headcount limits, shift tracking, and employee comparison.

  1. Import dataclass and field from the dataclasses module.
  2. Create an Employee dataclass with fields: name (str), emp_id (str), shifts_worked (int, default 0), and ratings (list of int, empty by default).
  3. Add a method log_shift(self, rating: int) that increments shifts_worked by 1 and appends the rating to the list.
  4. Add a method avg_rating(self) -> float that returns the average rating across all shifts, or 0.0 if no shifts have been logged.
  5. Create a Department dataclass with fields: dept_name (str), manager (str), headcount (int), employees (list of Employee, empty by default), and a computed field staff_count (int) that is not a constructor parameter. staff_count must reflect the current number of employees and stay accurate after every operation.
  6. Add a method hire(self, employee: Employee) -> bool that adds the employee only if the department is not full. Returns whether hiring succeeded.
  7. Add a method star_employee(self) -> str that returns the name of the employee with the highest average rating. If there are no employees or all averages are zero, return "No data".
  8. Add a method dept_stats(self) -> str that returns a formatted summary. Study the expected output to determine the exact format.

Input

e1 = Employee("Maya", "E201")
e2 = Employee("Ryan", "E202")
e3 = Employee("Zara", "E203")

e1.log_shift(4)
e1.log_shift(5)
e1.log_shift(3)
e2.log_shift(5)
e2.log_shift(5)
e3.log_shift(2)

d = Department("Engineering", "Dr. Patel", 3)
print(d.hire(e1))
print(d.hire(e2))
print(d.hire(e3))
print(d.hire(Employee("Leo", "E204")))
print(d.staff_count)
print(d.star_employee())
print(d.dept_stats())

Expected Output

True
True
True
False
3
Ryan
Engineering (Dr. Patel):
  Maya - 3 shifts, avg 4.0 rating
  Ryan - 2 shifts, avg 5.0 rating
  Zara - 1 shifts, avg 2.0 rating
Staff: 3/3

Variant 12: Event Catering Planner

You are building a catering estimation tool for events. Create a Supply dataclass and an Event dataclass that handles supply management, cost calculations, and scaling to different guest counts.

  1. Import dataclass and field from the dataclasses module.
  2. Create a Supply dataclass with fields: name (str), liters (float), and cost_per_liter (float).
  3. Add a method total_cost(self) -> float that returns liters * cost_per_liter.
  4. Create an Event dataclass with fields: title (str), guests (int), supplies (list of Supply, empty by default), and a computed field total_cost (float) that is not a constructor parameter. total_cost must be computed in __post_init__ as the sum of every supply’s cost, and must stay accurate after every operation.
  5. Add a method add_supply(self, supply: Supply) that adds the supply and updates total_cost.
  6. Add a method cost_per_guest(self) -> float that returns total_cost / guests.
  7. Add a method scale(self, new_guests: int) that adjusts every supply’s liters proportionally to the new guest count, updates guests, and recalculates total_cost.
  8. Add a method display(self) -> str that returns a formatted summary. Study the expected output to determine the exact format.

Input

e = Event("Gala Dinner", 50)
e.add_supply(Supply("Juice", 25.0, 4.0))
e.add_supply(Supply("Water", 50.0, 1.5))
e.add_supply(Supply("Coffee", 15.0, 6.0))

print(e.total_cost)
print(e.cost_per_guest())
print(e.display())

e.scale(25)
print(e.display())

Expected Output

265.0
5.3
Gala Dinner (50 guests):
  Juice: 25.0L ($100.0)
  Water: 50.0L ($75.0)
  Coffee: 15.0L ($90.0)
Per guest: $5.3

Gala Dinner (25 guests):
  Juice: 12.5L ($50.0)
  Water: 25.0L ($37.5)
  Coffee: 7.5L ($45.0)
Per guest: $5.3