-
-
Save ByteCommander/252a05032750cf4f6a25f2481581d2f1 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
#!/usr/bin/env python3 | |
def chopmax(seq, size): | |
rest = {} | |
for item, amount in seq: | |
while amount: | |
# print("item:", item, "- amount:", amount) | |
if not rest and amount >= size: | |
amount -= size | |
# print("chunk:", {item: size}) | |
yield item # uniform chunk | |
else: | |
missing = size - sum(rest.values()) | |
added = min(amount, missing) | |
rest[item] = rest.get(item, 0) + added | |
amount -= added | |
if added == missing: | |
# print("chunk:", rest) | |
yield max(rest.items(), key=lambda kv: kv[1])[0] | |
rest = {} | |
if rest: | |
# print("chunk:", rest) | |
yield max(rest.items(), key=lambda kv: kv[1])[0] | |
if __name__ == "__main__": | |
inp=[("a",2), ("b",7), ("c",3)] | |
print(inp, list(chopmax(inp, 5))) | |
inp=[("a", 21), ("b", 1), ("c", 5), ("d", 12)] | |
print(inp, list(chopmax(inp, 5))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment