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

问题描述 投票:1回答: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')
python product itertools gray-code
1个回答
0
投票

根据documentationitertools.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')
© www.soinside.com 2019 - 2024. All rights reserved.