Skip to content

Instantly share code, notes, and snippets.

@stephengruppetta
Created June 22, 2023 17:45
Show Gist options
  • Save stephengruppetta/e80a7b6a44678aa43404a6674332db4f to your computer and use it in GitHub Desktop.
Save stephengruppetta/e80a7b6a44678aa43404a6674332db4f 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment