Search code examples
pythonpowerset

How to print power set in order each pair of subset differs only one element?


I want to print a power set in an order such that adjacent subsets will differ by only one element.

For example:

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

Output would be printed like this:

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

or

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

Solution

  • Generate the first 2^N gray codes, where N = len(S). Use the bits of the code to select elements for that set.

    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)
    

    Output:

    []
    [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]