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.

4

1 回答 1

1

这个答案的基础上,我相信这会返回预期的结果:

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)

输入输出:

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

编辑:如果您需要传入一个负数,通过乘以 -1 在函数内部创建一个新变量,并在函数内部使用它而不是amount

于 2013-07-25T19:57:19.797 回答