A puzzle for Pythonistas

Magnus Lie Hetland mlh at furu.idi.ntnu.no
Wed Feb 5 22:07:44 EST 2003


In article <b68f71a7.0301310459.31539d3c at posting.google.com>, Alan
James Salmoni wrote:
>Hi folks,
>
>This is just a little puzzle to test your brains on - well, I should
>come clean really, so what I need to do is work out a way to get all
>the interactions from 2 or more variables for SalStat a small
>statistics package, but to be honest, I am rather stuck on this bit.
>
>The problem is defined like this: I have a list of unique integers,
>and the list is of arbitrary length, though 2 elements is the minimum.
>Using each integer only once, what are the possible combinations of 2
>or more elements that can be derived from this list. I know how to
>work out how many combinations there are: ((2**len(list))-1-len(list))
>which is quite simple.
[snip]
>I have a nasty feeling that the code may be complex, so feel free to
>tell me to s0d off if you want! :)

Although you have already received several answers, I can't resist
writing up a solution to this one... The code below creates all
subsets -- filtering out those of length 0 and 1 would, of course, be
trivial (and less general). Also, I'm using the compress() function
from numarray. Feel free to replace compress(cond, x) with a list
comprehension such as [x[i] for i in range(n) if cond[i]] if you don't
want to use numarray (or have numeric arrays returned).

from numarray import compress
def subsets(seq):
    n = len(seq)
    for i in xrange(2**n):
        cond = [bool(2<<j & i) for j in xrange(n)]
        yield compress(cond, seq)

-- 
Magnus Lie Hetland               "Nothing shocks me. I'm a scientist." 
http://hetland.org                                   -- Indiana Jones




More information about the Python-list mailing list