[Tutor] friday night entertainment (a generator)

Lloyd Kvam pythontutor at venix.com
Sat Oct 4 12:17:29 EDT 2003


One hidden bug, if passed an r of 0, but n is not empty, the
script continues to iterate through the list elements with negative r's.
These do no produce results so you won't notice unless you put a print
statement into the function.  I added:
     print "n,r,result",n,r,result
at the top and got these results:
n,r,result (1, 2, 3, 4) 2 ()
n,r,result [2, 3, 4] 1 (1,)
n,r,result [3, 4] 0 (1, 2)
(1, 2)
n,r,result [4] -1 (1, 2, 3)
n,r,result [] -2 (1, 2, 3, 4)
n,r,result [3] -1 (1, 2, 4)
n,r,result [] -2 (1, 2, 4, 3)
n,r,result [2, 4] 0 (1, 3)
(1, 3)
n,r,result [4] -1 (1, 3, 2)
<clipped>

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

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.

Gregor Lingl wrote:

> Hi,
> 
> I just wrote a generator which generates
> all the r-permutations of n distict objects,
> (this most probably is an old soup, newly cooked up -
> or a wheel reinvented):
> 
> def perms(n,r,result=()):
>    if r == 0:
>        yield result
>    for element in n:
>        t = n[:]
>        t.remove(element)
>        for perm in perms(t,r-1,result+(element,)):
>            yield perm
>           >>> for p in perms(range(4),2):
>    print p
> 
>   (0, 1)
> (0, 2)
> (0, 3)
> (1, 0)
> (1, 2)
> (1, 3)
> (2, 0)
> (2, 1)
> (2, 3)
> (3, 0)
> (3, 1)
> (3, 2)
>  >>>
> 
> Do any amendments (concerning efficiency and/or elegance)
> come to your mind?
> 
> Any hints or suggestions are highly appreciated
> 
> Gregor
> 
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 

-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice:	603-443-6155
fax:	801-459-9582




More information about the Tutor mailing list