带有Itertools的格雷码顺序的笛卡尔积? [英] Cartesian product in Gray code order with itertools?

查看:114
本文介绍了带有Itertools的格雷码顺序的笛卡尔积?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有类似Python的itertools.product()这样的东西,它以灰色代码顺序通过一组集合的笛卡尔积提供迭代?例如,假设存在这样一个假设生成器,并将其称为gray_code_product(),则gray_code_product(['a','b','c'], [0,1], ['x','y'])将按照以下顺序生成:

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? 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 :

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

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进行迭代,以确定索引是奇数还是偶数,并反转池的顺序(如果它是奇数):

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:

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

这篇关于带有Itertools的格雷码顺序的笛卡尔积?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆