acclivity

pyComputeChange

Dec 2nd, 2021 (edited)
591
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. # Compute Change using as few coins as possible
  2.  
  3. def getChange(price, tender):
  4.     coins = [500, 100, 50, 20, 10, 5, 2, 1, 0.5]
  5.     res = []                                        # This will be a list of coin quantities
  6.     change = 10 * (tender - price)                  # Multiplying by ten so that I can work with integer arithmetic
  7.     for c in coins:
  8.         rem, change = divmod(change, c * 10)        # Multiplying all coinage by 10  (0.5 becomes 5, for integer convenience)
  9.         res.append(rem)
  10.     return [(coins[x], int(res[x])) for x in range(len(coins)) if res[x]]
  11.  
  12. purchases = [["Bread", 28, 50], ["Pizza", 62, 100], ["Hamburger", 39.5, 100], ["Stuff", 50, 50]]
  13. for item, price, tender in purchases:
  14.     print(f"Item: {item},  Price: {price},  Money Tendered: {tender},  Change: {tender-price},   Units: {getChange(price, tender)}")
  15.  
  16. # Item: Bread,  Price: 28,  Money Tendered: 50,  Change: 22,   Units: [(20, 1), (2, 1)]
  17. # Item: Pizza,  Price: 62,  Money Tendered: 100,  Change: 38,   Units: [(20, 1), (10, 1), (5, 1), (2, 1), (1, 1)]
  18. # Item: Hamburger,  Price: 39.5,  Money Tendered: 100,  Change: 60.5,   Units: [(50, 1), (10, 1), (0.5, 1)]
  19. # Item: Stuff,  Price: 50,  Money Tendered: 50,  Change: 0,   Units: []
RAW Paste Data