Archive

Posts Tagged ‘itertools’

generate all subsets of a set

December 17, 2015 1 comment

Problem

Having a set, generate all its possible subsets. This time I had a list, but the problem is the same.

Solution

I found the answer here.

from itertools import chain, combinations

def all_subsets(ss):
    return chain(*map(lambda x: combinations(ss, x), range(0, len(ss)+1)))

for subset in all_subsets([1, 2, 3, 4]):
      print(subset)

Output:

()
(1,)
(2,)
(3,)
(4,)
(1, 2)
(1, 3)
(1, 4)
(2, 3)
(2, 4)
(3, 4)
(1, 2, 3)
(1, 2, 4)
(1, 3, 4)
(2, 3, 4)
(1, 2, 3, 4)
Categories: python Tags: , , ,