1

是否有类似 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')
4

1 回答 1

2

根据 的文档itertools.product该函数等价于以下 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)

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

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')
于 2020-04-10T22:43:20.773 回答