Skip to content

Instantly share code, notes, and snippets.

@stephengruppetta
Created June 22, 2023 17:47
Show Gist options
  • Save stephengruppetta/3769a99985760ebf2abb7f8e02ad1c89 to your computer and use it in GitHub Desktop.
Save stephengruppetta/3769a99985760ebf2abb7f8e02ad1c89 to your computer and use it in GitHub Desktop.
class Item:
def __init__(self, name, qty=0):
self.name = name
self.qty = qty
def __str__(self):
return f"{self.name} - {self.qty} left"
class VendingMachine:
def __init__(self):
self.items_on_sale = {}
def __getitem__(self, position):
row, column = position
if isinstance(row, int) and isinstance(column, int):
return self.items_on_sale[(row, column)]
raise TypeError("Requires two integer indices")
def add_item(self, item, row, column):
"""
Add an item to the vending machine at the required
row and column in the vending machine
:param item: Item object
:param row: int, row number
:param column: int, column number
"""
self.items_on_sale[(row, column)] = item
def buy_item(self, row, column):
item = self[row, column]
if item.qty > 0:
item.qty -= 1
return item.name
print("This slot is empty")
return None # Explicitly returning None, for clarity
hideous_machine = VendingMachine()
hideous_machine.add_item(Item("Hazelnut Chocolate", 5), 0, 0)
hideous_machine.add_item(Item("Dark Chocolate", 3), 0, 1)
hideous_machine.add_item(Item("Still Water", 7), 2, 2)
hideous_machine.add_item(Item("Sparkling Water", 4), 2, 1)
print(hideous_machine[2, 2])
hideous_machine.buy_item(2, 2)
print(hideous_machine[2, 2])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment