0

Working on a django project. On my payment model I have a simple def save

def save(self, *args, **kwargs):
    self.amount_change = self.amount_due - self.amount_paid
    return super(Payment, self).save(*args, **kwargs)

If my amount_change comes to -455.50 I'd like to return change as

  • 2x200
  • 1x50
  • 1x5
  • 1x0.5

What I'd like to do is breakdown the amount_change into the money denominations that I have and return the change to the client with the correct notes and or coins. My denominations are [200, 100, 50, 20, 10, 5, 1, 0.5]

How do I go about doing this? Any help is appreciated.

darren
  • 18,845
  • 17
  • 60
  • 79

1 Answers1

1

Building upon this answer, I believe this is returning the desired results:

from collections import Counter

def change(amount):
    money = ()

    for coin in [200, 100, 50, 20, 10, 5, 1, 0.5]:
        num = int(amount/coin)
        money += (coin,) * num
        amount -= coin * num

    return Counter(money)

Input and output:

>>> c = change(455.50)
>>> print c
Counter({200: 2, 0.5: 1, 50: 1, 5: 1})

Edit: If you need to pass in a negative number, create a new variable inside the function by multiplying by -1 and use it inside the function instead of amount

Community
  • 1
  • 1
Scott Woodall
  • 10,456
  • 6
  • 39
  • 37
  • Thanks for your help. I think another way was to use the other method you pointed me to and just push everything to cent value so that there are no fractions. However your solution is much more elegant. – darren Jul 25 '13 at 21:09