A puzzle for Pythonistas

Alan James Salmoni alan_salmoni at yahoo.com
Sat Feb 1 08:42:52 EST 2003


Thanks Alex,

Alex Martelli <aleax at aleax.it> wrote in message news:<0Kv_9.109127$0v.3149263 at news1.tin.it>...
> 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

Cos I'm not that good a programmer (self taught etc)! ;)

Alan.




More information about the Python-list mailing list