python - 通过一组槽尽可能均匀地分配整数数量
问题描述
我试图找出一种优雅的方式来实现将金额分配到python中给定的一组插槽中。
例如:
分布在 4 个盘子上的 7 个橙子将返回:
[2, 2, 2, 1]
4 个盘子中的 10 个橙子将是:
[3, 3, 2, 2]
解决方案
从概念上讲,您要做的是计算7 // 4 = 1
和7 % 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]
推荐阅读
- google-app-maker - 尽管数据源中要求表单提交空值(Google App Maker)
- google-schemas - 填写Email Markup注册后无反应
- css - 响应式媒体查询品牌标志
- python - 在bash中检查scrapy结果
- javascript - 另一个函数内的离子调用函数(JS服务)
- java - 强制 Hikari/Hibernate 关闭陈旧(泄露?)的连接
- android - 我们可以为 SQLLite 保留一个公共存储库,Android 应用程序可以在其中执行 CRUD 操作吗?
- mysql - 两个请求之一使我的服务器崩溃。有人知道吗?MYSQL
- android - Android - 如何使用线性布局触发 setOnCheckedChangeListener?
- node.js - React 应用程序无法将内容加载到浏览器