在Python中设置集合产品
一个集合 S 的 n 次笛卡尔积用 Sn 来表示。简单来说,就是把这个集合复制 n 次。比如说,{0, 1}3 就是所有可能的 3 位二进制序列:
{0,1}3 = {(0,0,0),(0,0,1),(0,1,0),(0,1,1),(1,0,0),(1,0,1),(1,1,0),(1,1,1)}
那么,在 Python 中,最简单的方法来实现这个想法是什么呢?
4 个回答
1
马克,这个主意不错。
>>> def set_product(the_set, n):
return set(itertools.product(the_set, repeat=n))
>>> s2 = set((0,1,2))
>>> set_product(s2, 3)
set([(0, 1, 1), (0, 1, 2), (1, 0, 1), (0, 2, 1), (2, 2, 0), (0, 2, 0), (0, 2, 2), (1, 0, 0), (2, 0, 1), (1, 2, 0), (2, 0, 0), (1, 2, 1), (0, 0, 2), (2, 2, 2), (1, 2, 2), (2, 0, 2), (0, 0, 1), (0, 0, 0), (2, 1, 2), (1, 1, 1), (0, 1, 0), (1, 1, 0), (2, 1, 0), (2, 2, 1), (2, 1, 1), (1, 1, 2), (1, 0, 2)])
你也可以扩展集合类型,然后让 __pow__
这个方法来实现这个功能。
3
我想这个可以用吧?
>>> s1 = set((0,1))
>>> set(itertools.product(s1,s1,s1))
set([(0, 1, 1), (1, 1, 0), (1, 0, 0), (0, 0, 1), (1, 0, 1), (0, 0, 0), (0, 1, 0), (1, 1, 1)])
17
在Python 2.6或更新的版本中,你可以使用itertools.product这个功能,并且可以选择性地使用一个叫repeat
的参数:
>>> from itertools import product
>>> s1 = set((0, 1))
>>> set(product(s1, repeat = 3))
如果你使用的是更早版本的Python,可以按照文档中的代码来实现product
功能:
def product(*args, **kwds):
# product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
# product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111
pools = map(tuple, args) * kwds.get('repeat', 1)
result = [[]]
for pool in pools:
result = [x+[y] for x in result for y in pool]
for prod in result:
yield tuple(prod)