给定一个整数和 bin 的数量,如何将整数分成尽可能相等的部分?
例如。输出的总和应等于输入整数
[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
or numpy
?
Using numpy
from https://stackoverflow.com/a/48899071/610569,我也可以这样做:
list(map(len, np.array_split(range(x), num_bins)))
但这与创建一个生成来获取假装列表并获取长度有点复杂。