Created
September 4, 2019 09:00
-
-
Save alex-1q84/dd54faea170acd140fc38bddb299bfb0 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 | |
# -*- coding: utf-8 -*- | |
import pprint | |
class Node: | |
def __init__(self, id, count): | |
self.id = id | |
self.count = count | |
def __repr__(self): | |
return f"({self.id}, {self.count})" | |
class NodeGroup(list): | |
def __init__(self): | |
self.value = 0 | |
def append(self, node): | |
self.value += node.count | |
return super().append(node) | |
def __repr__(self): | |
return "value: {}, {}".format(self.value, super().__repr__()) | |
def group(data, amount): | |
data.sort(key=lambda node: node.count, reverse=True) | |
# init result group | |
result = [NodeGroup() for i in range(amount)] | |
for node in data: | |
# find a most match position to insert this node | |
result[minimum(result)].append(node) | |
return result | |
def minimum(ldata): | |
'''return the minimum data index of ldata''' | |
if not ldata: | |
raise Exception("param is empty") | |
result = 0 | |
for i, node in enumerate(ldata): | |
if ldata[result].value > node.value: | |
result = i | |
return result | |
if __name__ == "__main__": | |
data = [Node(n, n) for n in [28, 25, 19, 18, 10, 9, 6, 4, 3, 1]] | |
result = group(data, 3) | |
pprint.pprint(result) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment