使用 itertools 的格雷码顺序的笛卡尔积?

Cartesian product in Gray code order with itertools?

有没有类似Python的itertools.product()的东西,通过格雷码阶中一组集合的笛卡尔积提供迭代?例如,假设存在这样一个假设的生成器,它被称为gray_code_product(),那么gray_code_product(['a','b','c'], [0,1], ['x','y'])将生成,顺序为:

('a',0,'x')
('a',0,'y')
('a',1,'y')
('a',1,'x')
('b',1,'x')
('b',1,'y')
('b',0,'y')
('b',0,'x')
('c',0,'x')
('c',0,'y')
('c',1,'y')
('c',1,'x')

根据itertools.productdocumentation,函数等价于下面的Python代码:

def product(*args, repeat=1):
    pools = [tuple(pool) for pool in args] * repeat
    result = [[]]
    for pool in pools:
        result = [x+[y] for x in result for y in pool]
    for prod in result:
        yield tuple(prod)

由于格雷码产品是关于反转每个池的前面序列的顺序,您可以在前面的 result 列表上使用 enumerate 迭代它以确定索引是否是奇数或偶数,如果是奇数则反转池的顺序:

def gray_code_product(*args, repeat=1):
    pools = [tuple(pool) for pool in args] * repeat
    result = [[]]
    for pool in pools:
        result = [x+[y] for i, x in enumerate(result) for y in (
            reversed(pool) if i % 2 else pool)]
    for prod in result:
        yield tuple(prod)

这样:

for p in gray_code_product(['a','b','c'], [0,1], ['x','y']):
    print(p)

输出:

('a', 0, 'x')
('a', 0, 'y')
('a', 1, 'y')
('a', 1, 'x')
('b', 1, 'x')
('b', 1, 'y')
('b', 0, 'y')
('b', 0, 'x')
('c', 0, 'x')
('c', 0, 'y')
('c', 1, 'y')
('c', 1, 'x')