Home > python > generate all subsets of a set

generate all subsets of a set

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)
Advertisements
Categories: python Tags: , , ,
  1. October 5, 2017 at 10:18

    They aren’t distinct, can you provide for distinct subsets?

  1. No trackbacks yet.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: