我正在尝试创建一系列项目的限制排列。每个项目都有一个类别,我需要找到项目的组合,这样每个组合都没有来自同一类别的多个项目。为了说明,这里有一些示例数据:
Name | Category
==========|==========
1. Orange | fruit
2. Apple | fruit
3. GI-Joe | toy
4. VCR | electronics
5. Racquet | sporting goods
组合将限制为三个长度,我不需要每个长度的每个组合。因此,以上列表的一组组合可以是:
(Orange, GI-Joe, VCR)
(Orange, GI-Joe, Racquet)
(Orange, VCR, Racquet)
(Apple, GI-Joe, VCR)
(Apple, GI-Joe, Racquet)
... and so on.
我经常在各种名单上这样做。这些列表的长度永远不会超过40个,但可以理解的是,它可以创建数千个组合(尽管每个列表可能会有大约10个唯一类别,但在某种程度上限制了它)
我已经提出了一些伪python,我将如何递归地实现它。自从我采用组合学以来已经太久了,但是我记得这基本上是该组合的一个子集,比如C(列表长度,所需大小)。可能有一些库模块可以使这个更清洁(或至少更高性能)
我想知道是否有比我更好的方法(也许是以某种方式使用itertools.combinations
的方法):
# For the sake of this problem, let's assume the items are hashable so they
# can be added to a set.
def combinate(items, size=3):
assert size >=2, "You jerk, don't try it."
def _combinate(index, candidate):
if len(candidate) == size:
results.add(candidate)
return
candidate_cats = set(x.category for x in candidate)
for i in range(index, len(items)):
item = items[i]
if item.category not in candidate_cats:
_combinate(i, candidate + (item, ))
results = set()
for i, item in enumerate(items[:(1-size)]):
_combinate(i, (item, ))
return results
答案 0 :(得分:2)
天真的方法:
#!/usr/bin/env python
import itertools
items = {
'fruits' : ('Orange', 'Apple'),
'toys' : ('GI-Joe', ),
'electronics' : ('VCR', ),
'sporting_goods' : ('Racquet', )
}
def combinate(items, size=3):
if size > len(items):
raise Exception("Lower the `size` or add more products, dude!")
for cats in itertools.combinations(items.keys(), size):
cat_items = [[products for products in items[cat]] for cat in cats]
for x in itertools.product(*cat_items):
yield zip(cats, x)
if __name__ == '__main__':
for x in combinate(items):
print x
将屈服:
# ==>
#
# [('electronics', 'VCR'), ('toys', 'GI-Joe'), ('sporting_goods', 'Racquet')]
# [('electronics', 'VCR'), ('toys', 'GI-Joe'), ('fruits', 'Orange')]
# [('electronics', 'VCR'), ('toys', 'GI-Joe'), ('fruits', 'Apple')]
# [('electronics', 'VCR'), ('sporting_goods', 'Racquet'), ('fruits', 'Orange')]
# [('electronics', 'VCR'), ('sporting_goods', 'Racquet'), ('fruits', 'Apple')]
# [('toys', 'GI-Joe'), ('sporting_goods', 'Racquet'), ('fruits', 'Orange')]
# [('toys', 'GI-Joe'), ('sporting_goods', 'Racquet'), ('fruits', 'Apple')]
答案 1 :(得分:1)
您要生成的内容是从category
集中获取的元素的笛卡尔product。
分成多个集合相对容易:
item_set[category].append(item)
对item_set[category]
进行适当的实例化(例如)collections.defaultdict,然后itertools.product
将为您提供所需的输出。