A puzzle for Pythonistas

Alex Martelli aleax at aleax.it
Fri Jan 31 15:28:12 CET 2003


Alan James Salmoni wrote:
   ...
> 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

All combinations:

def allcombos(somelist):
    if not somelist:
        yield somelist
        return
    head, tail = somelist[:1], somelist[1:]
    for sublist in allcombos(tail):
        yield head + sublist
        yield sublist

(you'll need to add a "from __future__ import generators" at the
start of your module if you're using Python 2.2 rather than 2.3).

only those combinations of length 2 or more, if you need them
as a list:

longcombos = [ x for x in allcombos(somelist) if len(x) >= 2 ]

or if you need just to iterate on them, then another generator:

def filterlong(sequences, minlen=2):
    for sequence in sequences:
        if len(sequence) >= minlen:
            yield sequence

and

longcombos = filterlong(allcombos())

> I have a nasty feeling that the code may be complex, so feel free to

Why should it be complex...?


Alex





More information about the Python-list mailing list