如何按每对子集仅一个元素的顺序打印功率设置?

时间:2018-10-17 22:06:31

标签: python powerset

我要按顺序打印幂集,以使相邻的子集仅相差一个元素。

例如:

Input: S= {1,2,3,4}

输出将像这样打印:

{"",{1},{2}, {3}, {4} ,{4,1}, {4,2} ,{4,3},{3,1}...}

{"", {1}, {1,2}, {2}, {2,3}, ...}

1 个答案:

答案 0 :(得分:2)

生成前2 ^ N gray codes,其中N = len(S)。使用代码中的位为该集合选择元素。

S = [1, 2, 3, 4]

for i in range(2**len(S)):
    gray_code = i ^ (i >> 1)
    subset = [S[j] for j in range(len(S)) if gray_code & (1 << j) ]
    print(subset)

输出:

[]
[1]
[1, 2]
[2]
[2, 3]
[1, 2, 3]
[1, 3]
[3]
[3, 4]
[1, 3, 4]
[1, 2, 3, 4]
[2, 3, 4]
[2, 4]
[1, 2, 4]
[1, 4]
[4]