from dataclasses import dataclass
from typing import List, Dict, Tuple
from copy import deepcopy
@dataclass
class Item:
name: str
price: float
quantity: int
@dataclass
class Combo:
name: str
items: Dict[str, int] # item_name -> quantity required
discount: float
class Order:
def __init__(self):
self.original_items: Dict[str, Item] = {}
self.current_items: Dict[str, Item] = {}
self.applied_combos: List[Tuple[str, float]] = [] # (combo_name, discount)
self.total_discount: float = 0.0
def add_item(self, name: str, price: float, quantity: int) -> None:
"""Add an item to both original and processed items."""
if name in self.original_items:
self.original_items[name].quantity += quantity
else:
self.original_items[name] = Item(name, price, quantity)
if name in self.current_items:
self.current_items[name].quantity += quantity
else:
self.current_items[name] = Item(name, price, quantity)
def get_original_total(self) -> float:
"""Calculate total price of original order before discounts."""
return sum([Link] * [Link] for item in self.original_items.values())
def get_processed_total(self) -> float:
"""Calculate total price of processed items."""
return sum([Link] * [Link] for item in self.current_items.values())
def get_final_total(self) -> float:
"""Calculate final total after applying all discounts."""
return self.get_processed_total() - self.total_discount
def get_summary(self) -> str:
"""Get a formatted summary of the order."""
summary = []
# Original order
[Link]("Original Order:")
for item in self.original_items.values():
[Link](f"{[Link]}x {[Link]} (${[Link] *
[Link]:.2f})")
[Link](f"Original Total: ${self.get_original_total():.2f}\n")
# Applied combos
if self.applied_combos:
[Link]("Applied Combos:")
for combo_name, discount in self.applied_combos:
[Link](f"- {combo_name}: -${discount:.2f}")
[Link](f"Total Discount: -${self.total_discount:.2f}\n")
# Remaining items
if self.current_items:
[Link]("Remaining Items:")
for item in self.current_items.values():
[Link](f"{[Link]}x {[Link]} (${[Link] *
[Link]:.2f})")
# Final total
[Link](f"\nFinal Total: ${self.get_final_total():.2f}")
return "\n".join(summary)
class OrderManager:
def __init__(self):
[Link]: List[Combo] = []
def add_combo(self, name: str, items: Dict[str, int], discount: float) -> None:
"""Add a combo definition to the system."""
[Link](Combo(name, items, discount))
def can_apply_combo(self, combo: Combo, order: Order) -> bool:
"""Check if a combo can be applied to the order."""
for item_name, required_qty in [Link]():
if (item_name not in order.current_items or
order.current_items[item_name].quantity < required_qty):
return False
return True
def apply_combo(self, combo: Combo, order: Order) -> None:
"""Apply a combo to the order."""
if not self.can_apply_combo(combo, order):
raise ValueError(f"Cannot apply combo {[Link]}: insufficient items")
for item_name, qty in [Link]():
if order.current_items[item_name].quantity >= qty:
order.current_items[item_name].quantity -= qty
if order.current_items[item_name].quantity == 0:
del order.current_items[item_name]
order.total_discount += [Link]
order.applied_combos.append(([Link], [Link]))
def apply_all_possible_combos(self, order: Order) -> None:
"""Apply all possible combos to the order."""
while True:
combo_applied = False
for combo in [Link]:
while self.can_apply_combo(combo, order):
self.apply_combo(combo, order)
combo_applied = True
if not combo_applied:
break
def main():
# Initialize order manager and order
manager = OrderManager()
order = Order()
# Add items to order
order.add_item("Hamburger", 6.0, 2)
order.add_item("Hamburger", 6.0, 2) # Adding 4 hamburgers total
order.add_item("Fries", 3.0, 1)
order.add_item("Soda", 3.0, 1)
# Define combo in manager
manager.add_combo("Burger Meal",
{"Hamburger": 2, "Fries": 1},
discount=2.0)
# Apply combos to order
manager.apply_all_possible_combos(order)
# Print order summary
print(order.get_summary())
if __name__ == "__main__":
main()
Restaurant Table Management
from dataclasses import dataclass
from typing import List, Dict, Tuple
from datetime import datetime, timedelta
# Data classes for core entities
@dataclass
class Table:
table_id: int
capacity: int
@dataclass
class Reservation:
customer_name: str
table_id: int
time: datetime
num_guests: int
confirmed: bool = False
@dataclass
class MenuItem:
name: str
price: float
category: str # e.g., "Appetizer", "Main Course", "Dessert"
class Order:
def __init__(self):
[Link]: Dict[str, Tuple[MenuItem, int]] = {} # {item_name: (MenuItem,
quantity)}
[Link]: float = 0.0
self.discounts_applied: List[Tuple[str, float]] = [] # (description, discount
amount)
def add_item(self, menu_item: MenuItem, quantity: int) -> None:
if menu_item.name in [Link]:
[Link][menu_item.name] = (menu_item, [Link][menu_item.name][1] +
quantity)
else:
[Link][menu_item.name] = (menu_item, quantity)
[Link] += menu_item.price * quantity
def calculate_subtotal(self) -> float:
return sum([Link] * qty for item, qty in [Link]())
def apply_discount(self, description: str, discount: float) -> None:
[Link] -= discount
self.discounts_applied.append((description, discount))
def get_summary(self) -> str:
summary = ["Order Summary:"]
for item, qty in [Link]():
[Link](f"- {qty}x {[Link]} (${[Link]:.2f} each): ${qty *
[Link]:.2f}")
[Link](f"Subtotal: ${self.calculate_subtotal():.2f}")
if self.discounts_applied:
[Link]("Discounts:")
for desc, amt in self.discounts_applied:
[Link](f"- {desc}: -${amt:.2f}")
[Link](f"Final Total: ${[Link]:.2f}")
return "\n".join(summary)
class DiscountManager:
def __init__(self):
[Link]: List[Tuple[str, callable]] = [] # (description, discount_rule
function)
def add_discount_rule(self, description: str, rule: callable) -> None:
[Link]((description, rule))
def apply_discounts(self, order: Order) -> None:
for description, rule in [Link]:
discount = rule(order)
if discount > 0:
order.apply_discount(description, discount)
class RestaurantSystem:
def __init__(self):
[Link]: List[Table] = []
[Link]: List[Reservation] = []
[Link]: Dict[str, MenuItem] = {}
self.discount_manager = DiscountManager()
# Table Management
def add_table(self, table_id: int, capacity: int) -> None:
[Link](Table(table_id, capacity))
# Menu Management
def add_menu_item(self, name: str, price: float, category: str) -> None:
[Link][name] = MenuItem(name, price, category)
# Reservation Management
def make_reservation(self, customer_name: str, table_id: int, time: datetime,
num_guests: int) -> str:
table = next((t for t in [Link] if t.table_id == table_id), None)
if not table:
return "Error: Table not found."
if [Link] < num_guests:
return f"Error: Table {table_id} cannot seat {num_guests} guests."
# Check for reservation conflicts
for res in [Link]:
if res.table_id == table_id and abs(([Link] - time).total_seconds()) <
3600:
return f"Error: Table {table_id} is already reserved at
{[Link]('%I:%M %p')}."
reservation = Reservation(customer_name, table_id, time, num_guests,
confirmed=True)
[Link](reservation)
return f"Reservation confirmed for {customer_name} at Table {table_id}."
# Discount Rule Helpers
def add_discount_rule(self, description: str, rule: callable) -> None:
self.discount_manager.add_discount_rule(description, rule)
# Order Handling
def create_order(self) -> Order:
return Order()
def process_order(self, order: Order) -> str:
self.discount_manager.apply_discounts(order)
return order.get_summary()
# Main Function to Demonstrate the System
def main():
restaurant = RestaurantSystem()
# Add tables
restaurant.add_table(1, 4)
restaurant.add_table(2, 6)
# Add menu items
restaurant.add_menu_item("Pasta", 12.0, "Main Course")
restaurant.add_menu_item("Salad", 7.0, "Appetizer")
restaurant.add_menu_item("Ice Cream", 5.0, "Dessert")
# Add discount rules
restaurant.add_discount_rule("10% off orders above $50", lambda order: 0.1 *
order.calculate_subtotal() if order.calculate_subtotal() > 50 else 0)
restaurant.add_discount_rule("Buy 2 desserts, get 1 free", lambda order:
sum([Link] for item, qty in [Link]() if [Link] ==
"Dessert" and qty >= 3))
# Make reservations
print(restaurant.make_reservation("Alice", 1, datetime(2025, 1, 17, 19, 0), 3))
print(restaurant.make_reservation("Bob", 2, datetime(2025, 1, 17, 19, 0), 5))
# Create and process an order
order = restaurant.create_order()
order.add_item([Link]["Pasta"], 2)
order.add_item([Link]["Salad"], 1)
order.add_item([Link]["Ice Cream"], 3)
print(restaurant.process_order(order))
if __name__ == "__main__":
main()