Problem overview
You build a VendingMachine class for a machine that sells one kind of item at a fixed price. The machine keeps the money inserted so far, called the credit, sells an item when the credit is enough and gives the leftover credit back on request. A machine is created with VendingMachine(), with no arguments.
__init__(self)setsself.credit = 0andself.price = 150.insert(self, amount)addsamountto the credit. It prints and returns nothing.select(self)tries to buy one item and returns a string. When the credit is below the price it returns"Need N more", where N is the missing amount, and leaves the credit alone. Otherwise it subtracts the price from the credit and returns"Dispensing!". Exact payment works, and extra money stays in the credit.refund(self)returns the whole credit and resets it to 0.
In the driver, 50 is inserted and select answers Need 100 more. After 150 more the credit is 200, the machine dispenses and keeps 50, and the refund is 50. Next, 150 is exact payment, so it dispenses and the refund is 0. Finally 100 is 50 short, the credit stays 100, and the refund is 100.
Approach: state plus methods that change it
A class bundles data with the actions on that data. Here the data is two fields, credit and price. Each machine made from the class has its own copies, so one machine's credit never touches another's. Every method gets self, the machine it works on, and reads or updates the fields through it.
Think of each method by what it does to the state:
insertonly changes the state: it adds to the credit.selectreads the state and answers with text. It changes the credit only on a successful purchase.refundreturns the state and then resets it.
The key rule in select is to put the early exit first. If the credit is too low, the method returns the message straight away, before anything is subtracted. The code after the if then only runs when the credit covers the price, so it can subtract and dispense without another check.
Step by step
- Declare the class
VendingMachine. It is the blueprint for the machine's state and actions. - Add the constructor,
__init__(self). Python runs it when you writeVendingMachine(), andselfis the new machine. - Create
self.creditand start it at 0. A new machine holds no money. - Create
self.priceand set it to 150. Every item costs the same, and the price is set once when the machine is made. - Add
insert(self, amount)back at the class level. - Add
amounttoself.credit. Use+=so the new money joins what is already there. - Add
select(self), which tries to buy one item. - Check for too little money with an
ifthat comparesself.creditwithself.priceusing<. Because the test is "less than", a credit equal to the price gets past it. - Return the message inside the
if:"Need ", the missing amount," more". The missing amount is the price minus the credit, turned into a whole number withint()and then into text withstr()so it can join the string. This branch changes nothing. - Subtract the price from the credit, below the
ifand without extra indentation. The customer has paid, so the credit shrinks. - Return
"Dispensing!". This line is reached only when the credit covered the price. - Add
refund(self), which gives back the whole credit. - Save the credit in
rfirst. Once the credit is reset, the old value would be gone. - Set
self.creditback to 0. After a refund the machine holds no money. - Return
r, the money that was saved.
The solution in Python
class VendingMachine:
def __init__(self):
self.credit = 0
self.price = 150
def insert(self, amount):
self.credit += amount
def select(self):
if self.credit < self.price:
return "Need " + str(int(self.price - self.credit)) + " more"
self.credit -= self.price
return "Dispensing!"
def refund(self):
r = self.credit
self.credit = 0
return r
m = VendingMachine()
m.insert(50)
print(m.select())
m.insert(150)
print(m.select())
print("Refunded: " + str(int(m.refund())))
m.insert(150)
print(m.select())
print("Refunded: " + str(int(m.refund())))
m.insert(100)
print(m.select())
print("Refunded: " + str(int(m.refund())))
Python details worth a look
- Fields live on
self.self.creditandself.pricebelong to one machine, and every method reaches them throughself. The caller passes nothing forself:m.insert(50)hands the machinemover automatically. - Building the message. Joining text and numbers with
+needsstr(), because Python doesn't convert numbers on its own."Need " + 100 + " more"would raise aTypeError. Theint()also drops a fractional part: with 99.5 inserted, the message saysNeed 50 more. - Save, reset, return. In
refund, the credit goes intorbefore the reset. Returningself.creditafter setting it to 0 would always return 0. - Two return types.
selectreturns a string andrefundreturns a number. That is why the driver wraps the refund instr(int(...))before joining it to"Refunded: ", and prints theselectresults directly.
What the driver prints
Need 100 more
Dispensing!
Refunded: 50
Dispensing!
Refunded: 0
Need 50 more
Refunded: 100
Edge cases and common mistakes
- Exact payment. With a credit of exactly 150,
selectmust dispense. Using<=in the check would refuse it. - Subtracting on a miss. The "Need N more" path must leave the credit alone. A machine holding 100 answers
Need 50 moreand still holds 100, so a later refund returns 100. - Forgetting the subtraction. Without it, a customer who inserted 400 could buy again and again, and the refund would return too much. With it, 400 buys two items (
Dispensing!twice, leaving 100), and the third call answersNeed 50 more. - A second refund. Asking again right away returns 0, because the first refund reset the credit.
- Selling with no money. A new machine answers
Need 150 moreand its credit stays 0. - Printing instead of returning.
selectreturns its message. The driver is the one that prints it.
Testing
- A new machine,
select():Need 150 more, credit 0. - Insert 149,
select():Need 1 more, credit still 149. - Insert 400, then
select()three times:Dispensing!(credit 250),Dispensing!(credit 100),Need 50 more(credit 100). - Then
refund()twice: 100 and then 0.
