Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: create iterator through subsets of a set for a loop

Tags:

python

I have a sequence of consecutive integers, for example [1, 2, 3]. I'd like to create an iterator that goes through all the subsets of the set. In this case [], [1],...,[1,2,3]. How could I do this?

like image 894
user1802143 Avatar asked Nov 30 '13 06:11

user1802143


1 Answers

The itertools documentation contains a recipe for this construction under the name powerset, if that's what you need.

from itertools import chain, combinations

def powerset(iterable):
    "powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)"
    s = list(iterable)
    return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))
like image 146
Games Brainiac Avatar answered Oct 02 '22 12:10

Games Brainiac