0% found this document useful (0 votes)
4 views8 pages

Low Level Design

Uploaded by

manju yadav
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views8 pages

Low Level Design

Uploaded by

manju yadav
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

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(item.quantity * item.price for item in self.original_items.values())

def get_processed_total(self) -> float:


"""Calculate total price of processed items."""
return sum(item.quantity * item.price 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
summary.append("Original Order:")
for item in self.original_items.values():
summary.append(f"{item.quantity}x {item.name} (${item.quantity *
item.price:.2f})")
summary.append(f"Original Total: ${self.get_original_total():.2f}\n")

# Applied combos
if self.applied_combos:
summary.append("Applied Combos:")
for combo_name, discount in self.applied_combos:
summary.append(f"- {combo_name}: -${discount:.2f}")
summary.append(f"Total Discount: -${self.total_discount:.2f}\n")

# Remaining items
if self.current_items:
summary.append("Remaining Items:")
for item in self.current_items.values():
summary.append(f"{item.quantity}x {item.name} (${item.quantity *
item.price:.2f})")

# Final total
summary.append(f"\nFinal Total: ${self.get_final_total():.2f}")

return "\n".join(summary)

class OrderManager:
def __init__(self):
self.combos: List[Combo] = []

def add_combo(self, name: str, items: Dict[str, int], discount: float) -> None:
"""Add a combo definition to the system."""
self.combos.append(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 combo.items.items():
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 {combo.name}: insufficient items")

for item_name, qty in combo.items.items():


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 += combo.discount
order.applied_combos.append((combo.name, combo.discount))

def apply_all_possible_combos(self, order: Order) -> None:


"""Apply all possible combos to the order."""
while True:
combo_applied = False
for combo in self.combos:
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):
self.items: Dict[str, Tuple[MenuItem, int]] = {} # {item_name: (MenuItem,
quantity)}
self.total: 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 self.items:
self.items[menu_item.name] = (menu_item, self.items[menu_item.name][1] +
quantity)
else:
self.items[menu_item.name] = (menu_item, quantity)
self.total += menu_item.price * quantity

def calculate_subtotal(self) -> float:


return sum(item.price * qty for item, qty in self.items.values())

def apply_discount(self, description: str, discount: float) -> None:


self.total -= discount
self.discounts_applied.append((description, discount))

def get_summary(self) -> str:


summary = ["Order Summary:"]
for item, qty in self.items.values():
summary.append(f"- {qty}x {item.name} (${item.price:.2f} each): ${qty *
item.price:.2f}")
summary.append(f"Subtotal: ${self.calculate_subtotal():.2f}")
if self.discounts_applied:
summary.append("Discounts:")
for desc, amt in self.discounts_applied:
summary.append(f"- {desc}: -${amt:.2f}")
summary.append(f"Final Total: ${self.total:.2f}")
return "\n".join(summary)

class DiscountManager:
def __init__(self):
self.rules: List[Tuple[str, callable]] = [] # (description, discount_rule
function)

def add_discount_rule(self, description: str, rule: callable) -> None:


self.rules.append((description, rule))

def apply_discounts(self, order: Order) -> None:


for description, rule in self.rules:
discount = rule(order)
if discount > 0:
order.apply_discount(description, discount)

class RestaurantSystem:
def __init__(self):
self.tables: List[Table] = []
self.reservations: List[Reservation] = []
self.menu: Dict[str, MenuItem] = {}
self.discount_manager = DiscountManager()

# Table Management
def add_table(self, table_id: int, capacity: int) -> None:
self.tables.append(Table(table_id, capacity))

# Menu Management
def add_menu_item(self, name: str, price: float, category: str) -> None:
self.menu[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 self.tables if t.table_id == table_id), None)
if not table:
return "Error: Table not found."
if table.capacity < num_guests:
return f"Error: Table {table_id} cannot seat {num_guests} guests."

# Check for reservation conflicts


for res in self.reservations:
if res.table_id == table_id and abs((res.time - time).total_seconds()) <
3600:
return f"Error: Table {table_id} is already reserved at
{res.time.strftime('%I:%M %p')}."

reservation = Reservation(customer_name, table_id, time, num_guests,


confirmed=True)
self.reservations.append(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(item.price for item, qty in order.items.values() if item.category ==
"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(restaurant.menu["Pasta"], 2)
order.add_item(restaurant.menu["Salad"], 1)
order.add_item(restaurant.menu["Ice Cream"], 3)

print(restaurant.process_order(order))

if __name__ == "__main__":
main()

You might also like