number generator

Paul Rubin http
Wed Mar 14 02:53:00 EDT 2007


Paul Rubin <http://phr.cx@NOSPAM.invalid> writes:
>     # yield all partitions of n having length k, with many duplications
>     def _partitions(n,k):
>         if k==0: return
>         for i in xrange(1,n-k+1):
>             for p in partitions(n-i, k-1):
>                 yield (i,)+p

Bah, I managed to mess up the above function during transcription.
Corrected and sped-up version:

    # yield all partitions of n having length k, with many duplications
    def _partitions(n,k,low=1):
        if k==1:
            yield (n,)
            return
        for i in xrange(low, n-k+1):
            for p in _partitions(n-i, k-1, i):
                yield (i,)+p



More information about the Python-list mailing list