Powersets of a list?

Alex Martelli aleaxit at yahoo.com
Fri May 25 12:19:10 EDT 2001


"Emile van Sebille" <emile at fenx.com> wrote in message
news:9els3j$2kap$1 at ID-11957.news.dfncis.de...
> This seems to do it:
    [znip]
> > I was wondering if, given a list  [1,2,3], one can generate its power
set?

What about a concise form such as...:

def powerset(L):
    N = len(L)
    return [ [L[i] for i in range(N) if X&(1L<<i)]
        for X in range(2**N) ]

or, to avoid consuming too much memory, a class
whose instances 'are' sequences of L's subsets
might be quite appropriate here:

class Powerset:
    def __init__(self, L):
        self.L = L
        self.N = N
        self.S = N*N
    def __getitem__(self, x):
        if x<0: x+=self.S
        if x<0 or x>=self.S: raise IndexError,x
        return [self.L[i] for i in range(self.N)
            if x&(1L<<i)]

I haven't supported slicing in this example, but
it wouldn't be terribly hard.  Anyway, it lets
you do such typical tasks as:

    for sq in Powerset('ciao'):
        print ''.join(sq)


Alex






More information about the Python-list mailing list