[Tutor] friday night entertainment (a generator)
Gregor Lingl
glingl at aon.at
Fri Oct 3 16:03:48 EDT 2003
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
More information about the Tutor
mailing list