|
| 1 | +class CafeQueue: |
| 2 | + |
| 3 | + def __init__(self): |
| 4 | + self._queue = [] |
| 5 | + self._orders = {} |
| 6 | + self._togo = {} |
| 7 | + |
| 8 | + def __iter__(self): |
| 9 | + return CafeQueueIterator(self) |
| 10 | + |
| 11 | + def add_customer(self, customer, *orders, to_go=True): |
| 12 | + self._queue.append(customer) |
| 13 | + self._orders[customer] = tuple(orders) |
| 14 | + self._togo[customer] = to_go |
| 15 | + |
| 16 | + def __len__(self): |
| 17 | + return len(self._queue) |
| 18 | + |
| 19 | + def __contains__(self, customer): |
| 20 | + return (customer in self._queue) |
| 21 | + |
| 22 | + |
| 23 | +class CafeQueueIterator: |
| 24 | + |
| 25 | + def __init__(self, cafe_queue): |
| 26 | + self._cafe = cafe_queue |
| 27 | + self._position = 0 |
| 28 | + |
| 29 | + def __next__(self): |
| 30 | + try: |
| 31 | + customer = self._cafe._queue[self._position] |
| 32 | + except IndexError: |
| 33 | + raise StopIteration |
| 34 | + |
| 35 | + orders = self._cafe._orders[customer] |
| 36 | + togo = self._cafe._orders[customer] |
| 37 | + self._position += 1 |
| 38 | + |
| 39 | + return (customer, orders, togo) |
| 40 | + |
| 41 | + def __iter__(self): |
| 42 | + return self |
| 43 | + |
| 44 | + |
| 45 | +queue = CafeQueue() |
| 46 | +queue.add_customer('Newman', 'tea', 'tea', 'tea', 'tea', to_go=False) |
| 47 | +queue.add_customer('James', 'medium roast drip, milk, 2 sugar substitutes') |
| 48 | +queue.add_customer('Glen', 'americano, no sugar, heavy cream') |
| 49 | +queue.add_customer('Jason', 'pumpkin spice latte', to_go=False) |
| 50 | + |
| 51 | +print(len(queue)) # prints 4 |
| 52 | +print('Glen' in queue) # prints True |
| 53 | +print('Kyle' in queue) # prints False |
| 54 | + |
| 55 | + |
| 56 | +def brew(order): |
| 57 | + print(f"(Making {order}...)") |
| 58 | + return order |
| 59 | + |
| 60 | + |
| 61 | +for customer, orders, to_go in queue: |
| 62 | + for order in orders: brew(order) |
| 63 | + if to_go: |
| 64 | + print(f"Order for {customer}!") |
| 65 | + else: |
| 66 | + print(f"(Takes order to {customer})") |
0 commit comments