将整数拆分为垃圾箱 [英] Split an integer into bins

查看:55
本文介绍了将整数拆分为垃圾箱的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出一个整数和仓数,如何将整数分成尽可能相等的部分?

Given a single integer and the number of bins, how to split the integer into as equal parts as possible?

例如输出的总和应等于输入的整数

E.g. the sum of the outputs should be equals to the input integer

[in]: x = 20 , num_bins = 3
[out]: (7, 7, 6)

另一个

[in]: x = 20 , num_bins = 6
[out]: (4, 4, 3, 3, 3, 3)

我已经尝试过了:

x = 20
num_bins = 3
y = [int(x/num_bins)] * num_bins
for i in range(x%num_bins):
    y[i] += 1

它可以工作,但是必须有一种更简单/更好的方法,也许使用 bisect numpy ?

It works but there must be a simpler/better way, maybe using bisect or numpy?

使用 https://stackoverflow.com/a/48899071/610569 中的 numpy ,我也可以这样做:

Using numpy from https://stackoverflow.com/a/48899071/610569 , I could do this too:

list(map(len, np.array_split(range(x), num_bins)))

但是,创建一个生成一个假装列表并获取长度的生成有点令人费解.

But that's a little convoluted with creating a generate to get the a pretend list and getting the length.

推荐答案

内置 divmod 函数可能对此有用.

The built-in divmod function could be useful for this.

def near_split(x, num_bins):
    quotient, remainder = divmod(x, num_bins)
    return [quotient + 1] * remainder + [quotient] * (num_bins - remainder)

演示

In [11]: near_split(20, 3)
Out[11]: [7, 7, 6]
In [12]: near_split(20, 6)
Out[12]: [4, 4, 3, 3, 3, 3]

这篇关于将整数拆分为垃圾箱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆