Created
December 30, 2017 09:40
-
-
Save mherkazandjian/d2378b1988e99d38f366800491994241 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def split_to_uniform_ranges(n, n_parts): | |
""" | |
Split n into n_parts where the max difference among parts is 1 | |
:param int n: the number to be split | |
:param int n_parts: The number of parts with which n will be split | |
:return: n_part tuples that indicate the stat-end of the ranges | |
""" | |
n, n_parts = numpy.int32(n), numpy.int32(n_parts) | |
# compute the average size of each part and the remainder to be distributed | |
# among the parts | |
n_mean = numpy.int32(numpy.float64(n) / numpy.float64(n_parts)) | |
n_remaining = n % (n_mean * n_parts) | |
if n_remaining == 0: | |
# number of parts is an integer multiple of the original range, all | |
# the parts have the same range size | |
xs = numpy.arange(n_parts) * n_mean | |
xe = xs + n_mean | |
else: | |
# number of parts is not an integer multiple of the original range, | |
# distribute the remainder on the first parts. The remainder is always | |
# less than n_parts | |
_xs = numpy.arange(n_remaining) * (n_mean + 1) | |
_xe = _xs + (n_mean + 1) | |
xs = numpy.hstack( | |
( | |
_xs, | |
numpy.arange(n_parts - n_remaining) * n_mean + _xe[-1] | |
) | |
) | |
xe = numpy.hstack( | |
( | |
_xe, | |
numpy.arange(n_parts - n_remaining) * n_mean + _xe[-1] + n_mean | |
) | |
) | |
assert (xe - xs).sum() - n == 0 | |
return zip(xs, xe) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment