Unyeilding a permutation generator

sillyhat at yahoo.com sillyhat at yahoo.com
Sun Nov 2 22:34:40 CET 2008


Hello, can someone please help.

I found the following code at http://code.activestate.com/recipes/252178/

def all_perms(str):
    if len(str) <=1:
        yield str
    else:
        for perm in all_perms(str[1:]):
            for i in range(len(perm)+1):
                #nb str[0:1] works in both string and list contexts
                yield perm[:i] + str[0:1] + perm[i:]

which allows me to do things like

for x in  all_permx("ABCD"):
  print x

I believe it is making use of the plain changes / Johnson Trotter
algorithm.
Can someone please confirm?

Anyway what I want to do is experiment with code similar to this (i.e.
same algorithm and keep the recursion) in other languages,
particularly vbscript and wondered what it would look like if it was
rewritten to NOT use the yield statement - or at least if it was
amended so that it can be easily translated to other languages that
dont have python's yield statement. I think the statement "for perm in
all_perms(str[1:]):"  will be hardest to replicate in a recursive
vbscript program for example.

Thanks for any constructive help given.

Hal



More information about the Python-list mailing list