Powersets of a list?

Emile van Sebille emile at fenx.com
Fri May 25 16:56:52 CEST 2001


This seems to do it:



def toggle(pattern):
    if pattern[-1] == 0:
        pattern[-1] = 1
    else:
        pattern[-1] = 0
        pattern[:-1] = toggle(pattern[:-1])
    return pattern

def genNibbles(qty):
    rslt = [[0]*qty]
    for i in xrange(2**qty - 1):
        rslt.append(toggle(rslt[-1][:]))
    return rslt

def powerset(set):
    incl = genNibbles(len(set))
    sq = range(len(set))
    rslt = []
    for i in incl:
        sset = []
        for j in sq:
            if i[j] == 1:
                sset.append(set[j])
        rslt.append(sset)
    return rslt

print powerset([1,2,3])


HTH,

--

Emile van Sebille
emile at fenx.com

---------
"Roy Katz" <katz at Glue.umd.edu> wrote in message
news:Pine.GSO.4.21.0105250956170.9036-100000 at y.glue.umd.edu...
> Hello,
>
> I was wondering if, given a list  [1,2,3], one can generate its power set?
>
> thanks,
> Roey Katz
>
>





More information about the Python-list mailing list