Created
January 7, 2021 18:21
-
-
Save ricky-lim/c45f475f7014bfe64d68dda4a32e26e8 to your computer and use it in GitHub Desktop.
generate binning with a size, that accumulates to the count
This file contains 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
#!/usr/bin/env python | |
import math | |
def generate_bins(size: int, count: int): | |
""" | |
>>> list(generate_bins(size=100, count=300)) | |
[100, 100, 100] | |
>>> list(generate_bins(size=100, count=301)) | |
[100, 100, 100, 1] | |
>>> list(generate_bins(size=10, count=1)) | |
[1] | |
>>> list(generate_bins(size=10, count=19)) | |
[10, 9] | |
>>> list(generate_bins(size=-10, count=-19)) | |
Traceback (most recent call last): | |
... | |
ValueError: size and count > 0 | |
>>> list(generate_bins(size=-10, count=19)) | |
Traceback (most recent call last): | |
... | |
ValueError: size > 0 | |
>>> list(generate_bins(size=10, count=-19)) | |
Traceback (most recent call last): | |
... | |
ValueError: count > 0 | |
""" | |
if size <= 0 and count <= 0: | |
raise ValueError(f"size and count > 0") | |
if size <= 0: | |
raise ValueError(f"size > 0") | |
if count<= 0: | |
raise ValueError(f"count > 0") | |
number_bins = math.ceil(count / size) | |
for i in range(1, number_bins): | |
yield size | |
remainder = count % size | |
if remainder == 0: | |
yield size | |
else: | |
yield remainder | |
if __name__ == "__main__": | |
import doctest | |
doctest.testmod() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment