我需要一个生成器来获取一组“代理”和一组“项目”的输入,并生成每个代理获取相同数量项目的所有分区。例如:生成一个集合的所有相同大小的分区
>>> 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
@Highstaker是的,我认为项目的数量总是代理人数量的整数倍。 –
是否有重复的项目? –