Skip to content

Instantly share code, notes, and snippets.

@ricky-lim
Created January 7, 2021 18:21
Show Gist options
  • Save ricky-lim/c45f475f7014bfe64d68dda4a32e26e8 to your computer and use it in GitHub Desktop.
Save ricky-lim/c45f475f7014bfe64d68dda4a32e26e8 to your computer and use it in GitHub Desktop.
generate binning with a size, that accumulates to the count
#!/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