Last active
August 20, 2019 15:43
-
-
Save javidcf/6c96cd13b3c1895d08c3b2e7d7a12f8b to your computer and use it in GitHub Desktop.
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
# Split a number into parts with a fixed size unit size | |
def split_number(number, parts, unit, min_units=0): | |
current = [] | |
num_units = round(number / unit) | |
for c in _divide_number_rec(num_units, parts, min_units, current): | |
yield tuple(u * unit for u in c) | |
def _split_number_rec(num_units, parts, last_units, current): | |
if parts <= 0: | |
yield current | |
else: | |
min_units = last_units if parts > 1 else num_units | |
max_units = num_units // parts | |
for units in range(min_units, max_units + 1): | |
current.append(units) | |
yield from _split_number_rec(num_units - units, parts - 1, units, current) | |
current.pop() | |
# Get one combination | |
print(next(split_number(4.5, 3, 0.25))) | |
# (0.0, 0.0, 4.5) | |
# Get all combinations | |
print(*split_number(4.5, 3, 0.25), sep='\n') | |
# (0.0, 0.0, 4.5) | |
# (0.0, 0.25, 4.25) | |
# (0.0, 0.5, 4.0) | |
# ... |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment