[Tutor] friday night entertainment (a generator)

Gregor Lingl glingl at aon.at
Sat Oct 4 16:58:48 EDT 2003



Lloyd Kvam schrieb:

> One hidden bug, if passed an r of 0, but n is not empty, the
> ....
>
> Here's your updated code with two other minor changes:
>     force r to a reasonable value
>     force t to be a list in the case that n is a tuple

Thanks for your valuable comments. You pointed out a really
bad mistake. It came from transforming an ordinary function
with return statements into a generator. I overlooked that a
yield statement doesn't terminate the execution of a function/
generator. Have to be more careful next time.

Regards,

Gregor

>
> from __future__ import generators
> def perms(n,r,result=()):
>     #print "n,r,result",n,r,result
>     r = max(0, min(r, len(n)))  # r ranges from 0 to len(n)
>                                 # change to raise an exception if you 
> prefer
>     if r == 0:
>         yield result
>     else:
>         for element in n:
>             t = list(n[:])      # n could be a tuple
>             t.remove(element)
>             for perm in perms(t,r-1,result+(element,)):
>                 yield perm
>
> if __name__ == '__main__':
>     n = (1,2,3,4)
>     for p in perms(n,0):
>         print p
>     for p in perms(n,2):
>         print p
>
>
> Hope this helps. 


It did!




More information about the Tutor mailing list