python - Work out correct money denominations for change -
working on django project. on payment model have 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 amount_change comes -455.50
i'd return change as
- 2x200
- 1x50
- 1x5
- 1x0.5
what i'd breakdown amount_change money denominations have , return change client correct notes , or coins. denominations [200, 100, 50, 20, 10, 5, 1, 0.5]
how go doing this? appreciated.
building upon this answer, believe returning desired results:
from collections import counter def change(amount): money = () 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 , output:
>>> c = change(455.50) >>> print c counter({200: 2, 0.5: 1, 50: 1, 5: 1})
edit: if need pass in negative number, create new variable inside function multiplying -1 , use inside function instead of amount
Comments
Post a Comment