[SciPy-user] Finding all combinations of numbers

David Warde-Farley dwf at cs.toronto.edu
Sun Jan 13 02:05:08 EST 2008


On 13-Jan-08, at 1:34 AM, Andrew Straw wrote:

> def setOfSubsets(L):
>    """find all subsets of L
>
>    from Alex Martelli:
>    http://mail.python.org/pipermail/python-list/2001-January/067815.html
>    """
>    N = len(L)
>    return [ [ L[i] for i in range(N)
>                if X & (1L<<i) ]
>        for X in range(2**N) ]

Hi Andrew,

That's a clever little snippet. :)

Just to point out to Roger in case he wants to use it: if I read it  
correctly, it doesn't include L  (which is, like the empty set,  
unwanted in practice) because range(x) gives you [0,1,...x-1]. So for  
the list [1,2,3] it will return all subsets of size 1 and size 2, plus  
the empty list.

If you wanted to exclude the empty, replace range(2**N) with  
range(1,2**N), skipping the number 0. If you want it to include the  
entire list, make the upper limit 2**N+1.

Cheers,

DWF



More information about the SciPy-User mailing list