Distribute an integer amount by a set of slots as evenly as possible

  • A+
Category:Languages

I am trying to figure an elegant way of implementing the distribution of an amount into a given set of slots in python.

For example:

7 oranges distributed onto 4 plates would return:

[2, 2, 2, 1] 

 


Conceptually, what you want to do is compute 7 // 4 = 1 and 7 % 4 = 3. This means that all the plates get 1 whole orange. The remainder of 3 tells you that three of the plates get an extra orange.

The divmod builtin is a shortcut for getting both quantities simultaneously:

def distribute(oranges, plates):     base, extra = divmod(oranges, plates)     return [base + (i < extra) for i in range(plates)] 

With your example:

>>> distribute(oranges=7, plates=4) [2, 2, 2, 1] 

For completeness, you'd probably want to check that oranges is non-negative and plates is positive. Given those conditions, here are some additional test cases:

>>> distribute(oranges=7, plates=1) [7]  >>> distribute(oranges=0, plates=4) [0, 0, 0, 0]  >>> distribute(oranges=20, plates=2) [10, 10]  >>> distribute(oranges=19, plates=4) [5, 5, 5, 4]  >>> distribute(oranges=10, plates=4) [3, 3, 2, 2] 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: