首页 > 解决方案 > 通过一组槽尽可能均匀地分配整数数量

问题描述

我试图找出一种优雅的方式来实现将金额分配到python中给定的一组插槽中。

例如:

分布在 4 个盘子上的 7 个橙子将返回:

[2, 2, 2, 1]

4 个盘子中的 10 个橙子将是:

[3, 3, 2, 2]

标签: python

解决方案


从概念上讲,您要做的是计算7 // 4 = 17 % 4 = 3. 这意味着所有盘子都有 1 个完整的橙色。3 的其余部分告诉您,其中三个盘子会得到一个额外的橙色。

divmod内置是同时获取两个数量的快捷方式:

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

用你的例子:

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

为了完整起见,您可能需要检查它oranges是非负数plates还是正数。鉴于这些条件,这里有一些额外的测试用例:

>>> 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]

推荐阅读