Design a vending machine
medium 90 minBuild a vending machine around its money: coins in escrow, change from a limited box, stock by place, a slow motor that can jam, and several events that arrive at once.
Video lesson · Chapter 1 of 6
Make a prediction
See it run
Coins, pieces and three slow seconds: watch who owns each coin after every line.
Operations
A sale with change
Juice for 70, paid with a dollar. The box has one quarter and four dimes.
Step 1 of 7
Press C1
A dollar lies in escrow. It is still the customer's.
Step 1: Press C1
def buy(self, code): with self._lock: if self._busy: raise Busy() product = self._inventory.find(code) extra = sum(self._escrow) - product.cents if extra < 0: raise NotEnough(-extra) change = self._box.plan(extra, self._escrow) if change is None: raise NoChange(extra) self._inventory.claim(code) self._busy = True try: self._motor.drop(code) except Jammed: with self._lock: self._inventory.put_back(code) self._busy = False raise with self._lock: self._box.settle(self._escrow, change) self._escrow = [] self._busy = False return Sale(product, tuple(change))- Cost
- The motor
- Guarantee
- Money or product
Plan before claim, claim before drop, coins last.
In the real world
The same vending machine doing real jobs. Pick one and step through it.
Insert twice, choose, get 50 back.
Step 1 of 6
Waiting
Escrow is empty: idle.
Step 1: Waiting
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Money as a float
criticalTen times 0.1 is less than 1. A fair customer is refused.
Wrongbalance += 0.10Rightescrow.append(Coin.DIME) # whole centsChange after the product
criticalThe juice is out and the change does not exist.
Wrongmotor.drop(code)change = box.plan(extra, escrow)Rightchange = box.plan(extra, escrow)if change is None: raise NoChange(extra)motor.drop(code)A lock around the motor
criticalEverybody waits for three seconds, and the second press is queued.
Wrongwith self._lock: ... self._motor.drop(code)Rightwith self._lock: ... self._busy = Trueself._motor.drop(code)Taking the coins first
majorAfter a jam or a crash the refund needs change again, and may fail.
Wrongbox.add(escrow); escrow = []motor.drop(code)Rightmotor.drop(code)box.settle(escrow, change)Greedy over a limited box
majorIt refuses sales that are possible.
Wrongfor coin in sorted(stock, reverse=True): ...Rightbest = {0: []} # search all sumsCatching every error as a jam
majorA timeout is not a jam. The juice may have fallen.
Wrongexcept Exception: put_back(code)Rightexcept Jammed: put_back(code)
Interview tips
Open with
- Where is each coin?
- Escrow, box, customer.
- Refuse before anything moves.
Reject aloud
- A balance without coins.
- A class for each mood, for now.
- A global machine.
Prove it
- Count all coins after each step.
- Stop the motor, press again.
- Cut the journal after each line.
Never
- Print the change.
- Charge before the drop.
- Read busy as sold out.