Week 9 Assignment
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.
- Import
dataclassandfieldfrom thedataclassesmodule. - Create a
Productdataclass with fields:name(str),price(float), andquantity(int). - Add a method
value(self) -> floatthat returnsprice * quantity. - Create a
Warehousedataclass with fields:name(str),products(list ofProduct, empty by default), and a computed fieldtotal_value(float) that is not a constructor parameter.total_valuemust be computed in__post_init__as the sum of every product’s value, and must stay accurate after every operation. - Add a method
add_product(self, product: Product)that adds the product to the list and updatestotal_value. - Add a method
sell(self, product_name: str, qty: int) -> boolthat finds the product by name, reduces its quantity byqtyonly if enough stock exists, updatestotal_value, and returns whether the sale succeeded. - Add a method
restock(self, product_name: str, qty: int)that finds the product by name and increases its quantity byqty, then updatestotal_value. - Add a method
report(self) -> strthat 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.
- Import
dataclassandfieldfrom thedataclassesmodule. - Create a
Memberdataclass with fields:name(str),member_id(str),sessions_attended(int, default 0), andcalories_burned(list of int, empty by default). - Add a method
log_session(self, calories: int)that incrementssessions_attendedby 1 and appends the calories to the list. - Add a method
avg_calories(self) -> floatthat returns the average calories burned per session, or0.0if no sessions have been logged. - Create a
FitnessClassdataclass with fields:class_name(str),instructor(str),capacity(int),members(list ofMember, empty by default), and a computed fieldenrolled(int) that is not a constructor parameter.enrolledmust reflect the current number of members and stay accurate after every operation. - Add a method
enroll(self, member: Member) -> boolthat adds the member only if the class is not full. Returns whether enrollment succeeded. - Add a method
best_performer(self) -> strthat 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". - Add a method
class_stats(self) -> strthat 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.
- Import
dataclassandfieldfrom thedataclassesmodule. - Create an
Ingredientdataclass with fields:name(str),grams(float), andcalories_per_gram(float). - Add a method
total_calories(self) -> floatthat returnsgrams * calories_per_gram. - Create a
Recipedataclass with fields:title(str),servings(int),ingredients(list ofIngredient, empty by default), and a computed fieldtotal_calories(float) that is not a constructor parameter.total_caloriesmust be computed in__post_init__as the sum of every ingredient’s calories, and must stay accurate after every operation. - Add a method
add_ingredient(self, ingredient: Ingredient)that adds the ingredient and updatestotal_calories. - Add a method
calories_per_serving(self) -> floatthat returnstotal_calories / servings. - Add a method
scale(self, new_servings: int)that adjusts every ingredient’sgramsproportionally to the new serving count, updatesservings, and recalculatestotal_calories. - Add a method
display(self) -> strthat 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.
- Import
dataclassandfieldfrom thedataclassesmodule. - Create a
MenuItemdataclass with fields:name(str),price(float), andquantity(int). - Add a method
value(self) -> floatthat returnsround(price * quantity, 2). - Create a
Restaurantdataclass with fields:name(str),menu_items(list ofMenuItem, empty by default), and a computed fieldtotal_revenue(float) that is not a constructor parameter.total_revenuemust be computed in__post_init__as the rounded sum of every item’s value, and must stay accurate after every operation. - Add a method
add_item(self, item: MenuItem)that adds the item to the list and updatestotal_revenue. - Add a method
serve(self, item_name: str, qty: int) -> boolthat finds the item by name, reduces its quantity byqtyonly if enough servings exist, updatestotal_revenue, and returns whether the serve succeeded. - Add a method
resupply(self, item_name: str, qty: int)that finds the item by name and increases its quantity byqty, then updatestotal_revenue. - Add a method
report(self) -> strthat 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.
- Import
dataclassandfieldfrom thedataclassesmodule. - Create a
Studentdataclass with fields:name(str),student_id(str),assignments_done(int, default 0), andscores(list of int, empty by default). - Add a method
submit(self, score: int)that incrementsassignments_doneby 1 and appends the score to the list. - Add a method
avg_score(self) -> floatthat returns the average score across all submissions, or0.0if no assignments have been submitted. - Create a
Coursedataclass with fields:course_name(str),professor(str),capacity(int),students(list ofStudent, empty by default), and a computed fieldenrolled(int) that is not a constructor parameter.enrolledmust reflect the current number of students and stay accurate after every operation. - Add a method
enroll(self, student: Student) -> boolthat adds the student only if the course is not full. Returns whether enrollment succeeded. - Add a method
top_student(self) -> strthat returns the name of the student with the highest average score. If there are no students or all averages are zero, return"No data". - Add a method
course_stats(self) -> strthat 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.
- Import
dataclassandfieldfrom thedataclassesmodule. - Create a
Materialdataclass with fields:name(str),kilograms(float), andcost_per_kg(float). - Add a method
total_cost(self) -> floatthat returnskilograms * cost_per_kg. - Create a
Projectdataclass with fields:title(str),units(int),materials(list ofMaterial, empty by default), and a computed fieldtotal_cost(float) that is not a constructor parameter.total_costmust be computed in__post_init__as the sum of every material’s cost, and must stay accurate after every operation. - Add a method
add_material(self, material: Material)that adds the material and updatestotal_cost. - Add a method
cost_per_unit(self) -> floatthat returnstotal_cost / units. - Add a method
scale(self, new_units: int)that adjusts every material’skilogramsproportionally to the new unit count, updatesunits, and recalculatestotal_cost. - Add a method
display(self) -> strthat 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.
- Import
dataclassandfieldfrom thedataclassesmodule. - Create a
Bookdataclass with fields:title(str),price(float), andcopies(int). - Add a method
value(self) -> floatthat returnsround(price * copies, 2). - Create a
Bookstoredataclass with fields:name(str),books(list ofBook, empty by default), and a computed fieldtotal_stock_value(float) that is not a constructor parameter.total_stock_valuemust be computed in__post_init__as the rounded sum of every book’s value, and must stay accurate after every operation. - Add a method
add_book(self, book: Book)that adds the book to the list and updatestotal_stock_value. - Add a method
sell(self, title: str, qty: int) -> boolthat finds the book by title, reduces its copies byqtyonly if enough stock exists, updatestotal_stock_value, and returns whether the sale succeeded. - Add a method
restock(self, title: str, qty: int)that finds the book by title and increases its copies byqty, then updatestotal_stock_value. - Add a method
report(self) -> strthat 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.
- Import
dataclassandfieldfrom thedataclassesmodule. - Create a
Playerdataclass with fields:name(str),player_id(str),games_played(int, default 0), andpoints(list of int, empty by default). - Add a method
record_game(self, pts: int)that incrementsgames_playedby 1 and appends the points to the list. - Add a method
avg_points(self) -> floatthat returns the average points per game, or0.0if no games have been played. - Create a
Teamdataclass with fields:team_name(str),coach(str),max_roster(int),players(list ofPlayer, empty by default), and a computed fieldroster_size(int) that is not a constructor parameter.roster_sizemust reflect the current number of players and stay accurate after every operation. - Add a method
sign(self, player: Player) -> boolthat adds the player only if the roster is not full. Returns whether signing succeeded. - Add a method
mvp(self) -> strthat returns the name of the player with the highest average points. If there are no players or all averages are zero, return"No data". - Add a method
team_stats(self) -> strthat 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.
- Import
dataclassandfieldfrom thedataclassesmodule. - Create a
Componentdataclass with fields:name(str),units(float), andprice_per_unit(float). - Add a method
total_price(self) -> floatthat returnsunits * price_per_unit. - Create an
Assemblydataclass with fields:title(str),batch_size(int),components(list ofComponent, empty by default), and a computed fieldtotal_price(float) that is not a constructor parameter.total_pricemust be computed in__post_init__as the sum of every component’s price, and must stay accurate after every operation. - Add a method
add_component(self, component: Component)that adds the component and updatestotal_price. - Add a method
price_per_item(self) -> floatthat returnstotal_price / batch_size. - Add a method
scale(self, new_batch_size: int)that adjusts every component’sunitsproportionally to the new batch size, updatesbatch_size, and recalculatestotal_price. - Add a method
display(self) -> strthat 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.
- Import
dataclassandfieldfrom thedataclassesmodule. - Create a
Tooldataclass with fields:name(str),rate(float), andhours(int). - Add a method
cost(self) -> floatthat returnsround(rate * hours, 2). - Create a
Workshopdataclass with fields:name(str),tools(list ofTool, empty by default), and a computed fieldtotal_cost(float) that is not a constructor parameter.total_costmust be computed in__post_init__as the rounded sum of every tool’s cost, and must stay accurate after every operation. - Add a method
add_tool(self, tool: Tool)that adds the tool to the list and updatestotal_cost. - Add a method
use(self, tool_name: str, hrs: int) -> boolthat finds the tool by name, reduces its hours byhrsonly if enough hours remain, updatestotal_cost, and returns whether the usage succeeded. - Add a method
extend(self, tool_name: str, hrs: int)that finds the tool by name and increases its hours byhrs, then updatestotal_cost. - Add a method
report(self) -> strthat 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.
- Import
dataclassandfieldfrom thedataclassesmodule. - Create an
Employeedataclass with fields:name(str),emp_id(str),shifts_worked(int, default 0), andratings(list of int, empty by default). - Add a method
log_shift(self, rating: int)that incrementsshifts_workedby 1 and appends the rating to the list. - Add a method
avg_rating(self) -> floatthat returns the average rating across all shifts, or0.0if no shifts have been logged. - Create a
Departmentdataclass with fields:dept_name(str),manager(str),headcount(int),employees(list ofEmployee, empty by default), and a computed fieldstaff_count(int) that is not a constructor parameter.staff_countmust reflect the current number of employees and stay accurate after every operation. - Add a method
hire(self, employee: Employee) -> boolthat adds the employee only if the department is not full. Returns whether hiring succeeded. - Add a method
star_employee(self) -> strthat returns the name of the employee with the highest average rating. If there are no employees or all averages are zero, return"No data". - Add a method
dept_stats(self) -> strthat 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.
- Import
dataclassandfieldfrom thedataclassesmodule. - Create a
Supplydataclass with fields:name(str),liters(float), andcost_per_liter(float). - Add a method
total_cost(self) -> floatthat returnsliters * cost_per_liter. - Create an
Eventdataclass with fields:title(str),guests(int),supplies(list ofSupply, empty by default), and a computed fieldtotal_cost(float) that is not a constructor parameter.total_costmust be computed in__post_init__as the sum of every supply’s cost, and must stay accurate after every operation. - Add a method
add_supply(self, supply: Supply)that adds the supply and updatestotal_cost. - Add a method
cost_per_guest(self) -> floatthat returnstotal_cost / guests. - Add a method
scale(self, new_guests: int)that adjusts every supply’slitersproportionally to the new guest count, updatesguests, and recalculatestotal_cost. - Add a method
display(self) -> strthat 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