Search code examples
pythonpowerset

Python : Finding power set without using any inbuilt function like itertools etc


I am trying to find the power set using bit manipulation.I can generate all sets but they are not indexable. I could not save it as a list of list. I tried to find the solution over the internet but could not get the relevant information.

Here is the code I used.

n = int(input()) # Size of the array
noteValue = []   # Array whose power set is to be found
for i in range(n):
    noteValue.append(int(input()))


powerSet = []
for i in range(1<<n):
    for j in range(n):
        if (i & (1<<j) > 0 ):
            powerSet.append(noteValue[j])

print(powerSet)

Output:

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

Desired Output:

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

Solution

  • Actually you can use a temporary list sub like this example:

    powerSet = []
    for i in range(1<<n):
        # Add sub list 
        sub = []
        for j in range(n):
            if (i & (1<<j) > 0 ):
                # Append to sub list
                sub.append(noteValue[j])
        # Then append sub to pwerset after finishing the inner loop
        powerSet.append(sub)
    
    print(powerSet)
    

    So, with this input:

    2
    2
    3
    

    It will output:

    [[], [2], [3], [2, 3]]