如何打印幂集以便每对子集仅不同一个元素?
How to print power set in order each pair of subset differs only one element?
我想按顺序打印幂集,使得相邻子集仅相差一个元素。
例如:
Input: S= {1,2,3,4}
输出将像这样打印:
{"",{1},{2}, {3}, {4} ,{4,1}, {4,2} ,{4,3},{3,1}...}
或
{"", {1}, {1,2}, {2}, {2,3}, ...}
生成前 2^N gray codes,其中 N = len(S)。将代码的位用于该集合的 select 个元素。
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]
我想按顺序打印幂集,使得相邻子集仅相差一个元素。
例如:
Input: S= {1,2,3,4}
输出将像这样打印:
{"",{1},{2}, {3}, {4} ,{4,1}, {4,2} ,{4,3},{3,1}...}
或
{"", {1}, {1,2}, {2}, {2,3}, ...}
生成前 2^N gray codes,其中 N = len(S)。将代码的位用于该集合的 select 个元素。
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]