How to turn this function into a generator?

andrew cooke andrew at acooke.org
Fri May 9 14:12:03 EDT 2003


i've not tried to tidy anything so you can see the translation process.

andrew

from __future__ import generators # needed for Python 2.2

def genPartitions(m):
#    res []
    a = [0]*m
    def recPartition(m,B,N):
            if m == 0:
#                res.append(a[:N])
                yield a[:N]
            else:
                for i in range(1,min(B,m)+1):
                    a[N]=i
                    for res in recPartition(m-i,i,N+1): yield res
#                    recPartition(m-i,i,N+1)
#    recPartition(m,m,0)
    for res in recPartition(m,m,0): yield res
#    return res

def test():
    P = genPartitions(7)
    for x in P : print x

if __name__=='__main__':
    test()


anton at vredegoor.doge.nl said:

> Please have a look at the following function:
>
> def genPartitions(m):
>     res,a = [],[0]*m
>     def recPartition(m,B,N):
>             if m == 0:
>                 res.append(a[:N])
>             else:
>                 for i in range(1,min(B,m)+1):
>                     a[N]=i
>                     recPartition(m-i,i,N+1)
>     recPartition(m,m,0)
>     return res
>
> def test():
>     P = genPartitions(7)
>     for x in P : print x
>
> if __name__=='__main__':
>     test()
>
>
> I'd like to replace "res.append(a[:N])" with "yield a[:N]". Since the
> function works as is, it would be possible to first build a list and
> then generate its values one by one. I want to generate the values
> immediately however, without first storing them in a list.
>
> Ideas appreciated,
>
> Anton
>
> --
>
> intellectual property is a contradictio in terminis
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>


-- 
http://www.acooke.org/andrew





More information about the Python-list mailing list