Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on May 8th, 2012  |  syntax: None  |  size: 0.59 KB  |  hits: 12  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. from decimal import Decimal
  2.  
  3.  
  4. def distribute(amount, n, decimals=2):
  5.     """
  6.     Distribute an amount among n users.
  7.       * Returns a list of Decimals.
  8.  
  9.     >>> allocate(0.02, 3)
  10.     [Decimal('0.01'), Decimal('0.01'), Decimal('0.0')]
  11.  
  12.     >>> allocate(14.56, 3)
  13.     [Decimal('4.86'), Decimal('4.85'), Decimal('4.85')]
  14.    
  15.     >>> allocate(14.56, 3, 5)
  16.     [Decimal('4.85334'), Decimal('4.85333'), Decimal('4.85333')]
  17.     """
  18.     cut = 10 ** decimals
  19.     value = int(amount * cut)
  20.     base = value / n
  21.     rest = value % n
  22.     return [Decimal(str((base + int(i < rest)) / float(cut))) for i in xrange(n)]