How to get all subsets of a set? (powerset)

前端 未结 28 2512
庸人自扰
庸人自扰 2020-11-22 05:18

Given a set

{0, 1, 2, 3}

How can I produce the subsets:

[set(),
 {0},
 {1},
 {2},
 {3},
 {0, 1},
 {0, 2},
 {0, 3},
 {1, 2}         


        
28条回答
  •  灰色年华
    2020-11-22 05:49

    A simple way would be to harness the internal representation of integers under 2's complement arithmetic.

    Binary representation of integers is as {000, 001, 010, 011, 100, 101, 110, 111} for numbers ranging from 0 to 7. For an integer counter value, considering 1 as inclusion of corresponding element in collection and '0' as exclusion we can generate subsets based on the counting sequence. Numbers have to be generated from 0 to pow(2,n) -1 where n is the length of array i.e. number of bits in binary representation.

    A simple Subset Generator Function based on it can be written as below. It basically relies

    def subsets(array):
        if not array:
            return
        else:
            length = len(array)
            for max_int in range(0x1 << length):
                subset = []
                for i in range(length):
                    if max_int & (0x1 << i):
                        subset.append(array[i])
                yield subset
    

    and then it can be used as

    def get_subsets(array):
        powerset = []
        for i in subsets(array):
            powerser.append(i)
        return powerset
    

    Testing

    Adding following in local file

    if __name__ == '__main__':
        sample = ['b',  'd',  'f']
    
        for i in range(len(sample)):
            print "Subsets for " , sample[i:], " are ", get_subsets(sample[i:])
    

    gives following output

    Subsets for  ['b', 'd', 'f']  are  [[], ['b'], ['d'], ['b', 'd'], ['f'], ['b', 'f'], ['d', 'f'], ['b', 'd', 'f']]
    Subsets for  ['d', 'f']  are  [[], ['d'], ['f'], ['d', 'f']]
    Subsets for  ['f']  are  [[], ['f']]
    

提交回复
热议问题