是否有类似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的格雷码顺序的笛卡尔积?
发布评论