1 回答

TA貢獻1828條經驗 獲得超6個贊
根據 的文檔,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')
添加回答
舉報