Public paste
Undefined
By: Guest | Date: Jun 6 2018 20:52 | Format: Python | Expires: never | Size: 1.28 KB | Hits: 711

  1. from decimal import Decimal
  2.  
  3.  
  4. class ATM:
  5.     def __init__(self):
  6.         self.balances = {}
  7.  
  8.     def deposit(self, customer, amount):
  9.         amount = Decimal(amount)
  10.         if amount <= 0:
  11.             raise ValueError("Can only deposit positive amounts")
  12.         if customer in self.balances:
  13.             self.balances[customer] += amount
  14.         else:
  15.             self.balances[customer] = amount
  16.  
  17.     def withdraw(self, customer, amount):
  18.         if customer not in self.balances:
  19.             raise KeyError("No such customer: {}".format(customer))
  20.         amount = Decimal(amount)
  21.         balance = self.balances[customer]
  22.         if amount > balance:
  23.             raise ValueError("Overdraft")
  24.         self.balances[customer] = balance - amount
  25.  
  26.  
  27. if __name__ == '__main__':
  28.     atm = ATM()
  29.     atm.deposit('alice', '1200.63')
  30.     atm.deposit('bob', '686.95')
  31.     try:
  32.         atm.deposit('carol', '-13')
  33.         assert False, "Should have raised ValueError"
  34.     except ValueError:
  35.         pass
  36.     atm.deposit('bob', '.05')
  37.     assert atm.balances['bob'] == 687
  38.     atm.withdraw('alice', '.63')
  39.     assert atm.balances['alice'] == 1200
  40.     try:
  41.         atm.withdraw('danica', '12')
  42.         assert False, "Should have raised KeyError"
  43.     except KeyError:
  44.         pass