Partition Problem

Duncan Booth duncan at NOSPAMrcp.co.uk
Mon Jul 23 05:10:15 EDT 2001


Tom_Good1 at excite.com (Tom Good) wrote in 
news:ac677656.0107201451.6f5e120d at posting.google.com:

> And now, for something completely different!  "Fun with generators."
> 
> Here is the "sets of 6 positive integers that sum to 17" problem,
> solved with generators.  Works with Python 2.2.  My goal here was to
> minimize lines of code, not to optimize for performance.
> 
Followed by the 'how to iterate over all permutations of a sequence'. BTW, 
the 'return' statement isn't actually needed, but I think it makes the code 
a bit clearer.
--- begin ---
# Permutations using generators.
from __future__ import generators

def permute(seq):
    if len(seq)==1:
        yield seq
        return

    for i in range(len(seq)):
        for perm in permute(seq[:i] + seq[i+1:]):
            yield seq[i:i+1] + perm

def test(str):
    for t in permute(str):
        print t

test('bar')
test('flip')
test([1, 2, 3])
--- end ---


-- 
Duncan Booth                                             duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?



More information about the Python-list mailing list