|
| 1 | +""" |
| 2 | +Console-free grocery cart logic. |
| 3 | +""" |
| 4 | + |
| 5 | + |
| 6 | +class GroceryStoreCart: |
| 7 | + """ |
| 8 | + Maintain cart item quantities and compute totals. |
| 9 | +
|
| 10 | + >>> cart = GroceryStoreCart({"apple": 1.5, "milk": 2.0}) |
| 11 | + >>> cart.add_item("apple", 2) |
| 12 | + >>> cart.add_item("milk") |
| 13 | + >>> round(cart.total_price(), 2) |
| 14 | + 5.0 |
| 15 | + >>> cart.remove_item("apple") |
| 16 | + >>> round(cart.total_price(), 2) |
| 17 | + 3.5 |
| 18 | + """ |
| 19 | + |
| 20 | + def __init__(self, price_catalog: dict[str, float]) -> None: |
| 21 | + if not price_catalog: |
| 22 | + raise ValueError("price_catalog cannot be empty") |
| 23 | + self.price_catalog = dict(price_catalog) |
| 24 | + self.quantities: dict[str, int] = {} |
| 25 | + |
| 26 | + def add_item(self, item: str, quantity: int = 1) -> None: |
| 27 | + if item not in self.price_catalog: |
| 28 | + raise KeyError(f"{item!r} is not in the catalog") |
| 29 | + if quantity <= 0: |
| 30 | + raise ValueError("quantity must be positive") |
| 31 | + self.quantities[item] = self.quantities.get(item, 0) + quantity |
| 32 | + |
| 33 | + def remove_item(self, item: str, quantity: int = 1) -> None: |
| 34 | + if quantity <= 0: |
| 35 | + raise ValueError("quantity must be positive") |
| 36 | + current = self.quantities.get(item, 0) |
| 37 | + if current == 0: |
| 38 | + raise KeyError(f"{item!r} is not present in the cart") |
| 39 | + remaining = current - quantity |
| 40 | + if remaining > 0: |
| 41 | + self.quantities[item] = remaining |
| 42 | + else: |
| 43 | + self.quantities.pop(item, None) |
| 44 | + |
| 45 | + def total_price(self) -> float: |
| 46 | + return sum(self.price_catalog[item] * qty for item, qty in self.quantities.items()) |
| 47 | + |
| 48 | + |
| 49 | +if __name__ == "__main__": |
| 50 | + import doctest |
| 51 | + |
| 52 | + doctest.testmod() |
0 commit comments