Skip to content

Instantly share code, notes, and snippets.

@ByteCommander
Last active September 12, 2017 18:10
Show Gist options
  • Save ByteCommander/252a05032750cf4f6a25f2481581d2f1 to your computer and use it in GitHub Desktop.
Save ByteCommander/252a05032750cf4f6a25f2481581d2f1 to your computer and use it in GitHub Desktop.
#!/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