Split An Integer Into Bins
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
Solution 1:
The built-in divmod
function could be useful for this.
defnear_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]
Solution 2:
Updated simplified using integer arithmetic.
Here's a one-liner:
np.arange(n+k-1, n-1, -1) // k
Little demo:
>>> 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])
Post a Comment for "Split An Integer Into Bins"