|
| 1 | +from collections.abc import Collection, Iterator |
| 2 | +from abc import abstractmethod |
| 3 | + |
| 4 | + |
| 5 | +class CustomerQueue(Collection): |
| 6 | + |
| 7 | + @abstractmethod |
| 8 | + def add_customer(self, customer): pass |
| 9 | + |
| 10 | + @property |
| 11 | + @abstractmethod |
| 12 | + def first(self): pass |
| 13 | + |
| 14 | + |
| 15 | +class CafeQueue(CustomerQueue): |
| 16 | + |
| 17 | + def __init__(self): |
| 18 | + self._queue = [] |
| 19 | + self._orders = {} |
| 20 | + self._togo = {} |
| 21 | + |
| 22 | + def __iter__(self): |
| 23 | + return Iterator_CafeQueue(self) |
| 24 | + |
| 25 | + def __len__(self): |
| 26 | + return len(self._queue) |
| 27 | + |
| 28 | + def __contains__(self, customer): |
| 29 | + return (customer in self._queue) |
| 30 | + |
| 31 | + def add_customer(self, customer, *orders, to_go=True): |
| 32 | + self._queue.append(customer) |
| 33 | + self._orders[customer] = tuple(orders) |
| 34 | + self._togo[customer] = to_go |
| 35 | + |
| 36 | + @property |
| 37 | + def first(self): |
| 38 | + return self._queue[0] |
| 39 | + |
| 40 | + |
| 41 | +class Iterator_CafeQueue(Iterator): |
| 42 | + |
| 43 | + def __init__(self, iterable): |
| 44 | + self._iterable = iterable |
| 45 | + self._position = 0 |
| 46 | + |
| 47 | + def __next__(self): |
| 48 | + if self._position >= len(self._iterable): |
| 49 | + raise StopIteration |
| 50 | + |
| 51 | + customer = self._iterable._queue[self._position] |
| 52 | + orders = self._iterable._orders[customer] |
| 53 | + togo = self._iterable._togo[customer] |
| 54 | + |
| 55 | + self._position += 1 |
| 56 | + |
| 57 | + return (customer, orders, togo) |
| 58 | + |
| 59 | + def __iter__(self): |
| 60 | + return self |
| 61 | + |
| 62 | + |
| 63 | +def serve_customers(queue): |
| 64 | + if not isinstance(queue, CustomerQueue): |
| 65 | + raise TypeError("serve_next() requires a customer queue.") |
| 66 | + |
| 67 | + if not len(queue): |
| 68 | + print("Queue is empty.") |
| 69 | + return |
| 70 | + |
| 71 | + def brew(order): |
| 72 | + print(f"(Making {order}...)") |
| 73 | + |
| 74 | + for customer, orders, to_go in queue: |
| 75 | + for order in orders: brew(order) |
| 76 | + if to_go: |
| 77 | + print(f"Order for {customer}!") |
| 78 | + else: |
| 79 | + print(f"(Takes order to {customer})") |
| 80 | + |
| 81 | + |
| 82 | +queue = CafeQueue() |
| 83 | +queue.add_customer('Raquel', 'double macchiato', to_go=False) |
| 84 | +queue.add_customer('Naomi', 'large mocha, skim') |
| 85 | +queue.add_customer('Anmol', 'mango lassi') |
| 86 | + |
| 87 | +print(f"The first person in line is {queue.first}.") |
| 88 | +serve_customers(queue) |
0 commit comments