
Untitled
By: a guest on
May 8th, 2012 | syntax:
None | size: 0.59 KB | hits: 12 | expires: Never
from decimal import Decimal
def distribute(amount, n, decimals=2):
"""
Distribute an amount among n users.
* Returns a list of Decimals.
>>> allocate(0.02, 3)
[Decimal('0.01'), Decimal('0.01'), Decimal('0.0')]
>>> allocate(14.56, 3)
[Decimal('4.86'), Decimal('4.85'), Decimal('4.85')]
>>> allocate(14.56, 3, 5)
[Decimal('4.85334'), Decimal('4.85333'), Decimal('4.85333')]
"""
cut = 10 ** decimals
value = int(amount * cut)
base = value / n
rest = value % n
return [Decimal(str((base + int(i < rest)) / float(cut))) for i in xrange(n)]