用Python设置产品

Eug*_*ene 8 python math

集合S的n个副本的乘积表示为S 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中复制这个想法的最简单方法是什么?

Mar*_*ers 13

在Python 2.6或更高版本中,您可以将itertools.product与可选参数一起使用repeat:

>>> from itertools import product
>>> s1 = set((0, 1))
>>> set(product(s1, repeat = 3))
Run Code Online (Sandbox Code Playgroud)

对于旧版本的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)
Run Code Online (Sandbox Code Playgroud)