Divide an integer into cells

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

eg. the sum of the outputs must be equal to the input integer

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

Another, for example.

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

I tried this:

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

This works, but there should be an easier / better way, perhaps using bisector numpy?

Using numpyfrom https://stackoverflow.com/a/3/2/2/9 , I could do this too:

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

But this is a bit confusing with creating a generation to get a fake list and get the length.

+6
source share
2 answers

divmod.

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

Demo

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

.

:

np.arange(n+k-1, n-1, -1) // k

:

>>> for k in range(4, 10, 3):
...     for n in range(10, 17):
...         np.arange(n+k-1, n-1, -1) // k
... 
array([3, 3, 2, 2])
array([3, 3, 3, 2])
array([3, 3, 3, 3])
array([4, 3, 3, 3])
array([4, 4, 3, 3])
array([4, 4, 4, 3])
array([4, 4, 4, 4])
array([2, 2, 2, 1, 1, 1, 1])
array([2, 2, 2, 2, 1, 1, 1])
array([2, 2, 2, 2, 2, 1, 1])
array([2, 2, 2, 2, 2, 2, 1])
array([2, 2, 2, 2, 2, 2, 2])
array([3, 2, 2, 2, 2, 2, 2])
array([3, 3, 2, 2, 2, 2, 2])
+2

All Articles