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

编程入门 行业动态 更新时间:2024-10-09 14:18:36
本文介绍了带有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')

推荐答案

根据itertools.product的nofollow noreferrer>文档,该功能等效于以下Python代码:

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的格雷码顺序的笛卡尔积?

本文发布于:2023-11-29 09:33:31,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1646016.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:笛卡尔   格雷   顺序   Itertools

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!