【发布时间】:2017-02-17 06:28:08
【问题描述】:
我需要一个生成器,它将一组“代理”和一组“项目”作为输入,并生成每个代理获得相同数量项目的所有分区。例如:
>>> for p in equalPartitions(["A","B"], [1,2,3,4]): print(p)
{'A': [1, 2], 'B': [3, 4]}
{'A': [1, 3], 'B': [2, 4]}
{'A': [1, 4], 'B': [2, 3]}
{'A': [2, 3], 'B': [1, 4]}
{'A': [2, 4], 'B': [1, 3]}
{'A': [3, 4], 'B': [1, 2]}
对于两个代理来说,这很容易(假设项目数是偶数):
itemsPerAgent = len(items) // len(agents)
for bundle0 in itertools.combinations(items, itemsPerAgent):
bundle1 = [item for item in items if item not in bundle0]
yield {
agents[0]: list(bundle0),
agents[1]: bundle1
}
对于三个代理,这变得更加复杂:
itemsPerAgent = len(items) // len(agents)
for bundle0 in itertools.combinations(items, itemsPerAgent):
bundle12 = [item for item in items if item not in bundle0]
for bundle1 in itertools.combinations(bundle12, itemsPerAgent):
bundle2 = [item for item in bundle12 if item not in bundle1]
yield {
agents[0]: list(bundle0),
agents[1]: list(bundle1),
agents[2]: bundle2
}
是否有更通用的解决方案,适用于任意数量的代理?
【问题讨论】:
-
只是为了澄清。您是否总是有可以在代理之间平均分配的项目数量(
len(items)/len(agents) == 0)?如果没有,如果物品不能均匀分配,你如何在代理之间分配物品? -
@Highstaker 是的,我假设物品的数量总是代理人数量的整数倍。
-
是否有重复项?
标签: python algorithm python-3.x combinations partitioning