Skip to content

Instantly share code, notes, and snippets.

@jorgebastida
Created August 6, 2011 22:59
Show Gist options
  • Save jorgebastida/1129856 to your computer and use it in GitHub Desktop.
Save jorgebastida/1129856 to your computer and use it in GitHub Desktop.
Distribute an amount among n users.
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)]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment