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

前端 未结 5 509
逝去的感伤
逝去的感伤 2021-02-02 09:47

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

5条回答
  •  时光取名叫无心
    2021-02-02 10:00

    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]
    

提交回复
热议问题