Unyeilding a permutation generator
Steve Holden
steve at holdenweb.com
Sun Nov 2 22:24:08 EST 2008
sillyhat at yahoo.com wrote:
> 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.
>
There are various approaches you could use, the simplest of which is to
provide a "callback function" as an additional argument to the all_perms
function, and call it with the permutation as an argument in place of
the yield statement.
regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
Holden Web LLC http://www.holdenweb.com/
More information about the Python-list
mailing list