python - 带有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.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')
推荐阅读
- javascript - 如何在单独的 HTML 网站上重用这个响应式导航栏
- python - 如何使postgresql中的每一列分别唯一?
- r - 无法再安装任何 R 包
- android - 在 android MediaPlayer 中播放来自 Firebase 存储的音频文件
- android - 如何在 android Oreo 中自动启用 GPS?
- android - 设备不适用于“main.dart”配置,
- javascript - 如何编写正则表达式不允许开头和结尾有空格,但单词之间需要空格
- java - 有没有办法从矩阵中以数组的形式访问列的引用?
- aws-lambda - 代码管道 lambda 操作永远不会完成
- c# - 即使在 c# 中事件完成后也可以存储和保留变量的值