简体   繁体   English

带有itertools的格雷码顺序的笛卡尔积?

[英]Cartesian product in Gray code order with itertools?

Is there something like Python's itertools.product() that provides the iteration through the Cartesian product of a set of sets in Gray code order ?是否有类似 Python 的itertools.product()提供通过格雷码顺序集合的笛卡尔积的迭代? For example, supposing that such a hypothetical generator existed, and it was called gray_code_product() , then gray_code_product(['a','b','c'], [0,1], ['x','y']) would generate, in the order:例如,假设存在这样一个假设的生成器,它被称为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')

According to the documentation of itertools.product , the function is equivalent to the following Python code:根据itertools.product文档, function 等效于以下 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)

Since a gray code product is about reversing the order of the preceding sequence for each pool, you can use enumerate on the previous result list while iterating over it to determine if the index is odd or even-numbered, and reverse the sequence of the pool if it's odd-numbered:由于格雷码积是关于反转每个池的前一个序列的顺序,因此您可以在迭代它的同时对前一个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)

so that:以便:

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

outputs:输出:

('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')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM