Steve Holden wrote:
[EMAIL PROTECTED] wrote:

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.

I had thought of three ways to avoid yield, that makes a fourth.

Summary:

1. Think of generator function as an abbreviated iterator class and unabbreviate by writing a full iterator class with .__next__ (3.0).
+ Transparent to caller
- Will often have to re-arrange code a bit to save locals values as attributes before returning. If there is an inner loop, efficiency may require copying attributes to locals.

2. Add to collection rather than yield, then return collection rather than raise StopIteration.
+ Transparent to caller; small change to function.
- Returned collection can be arbitrarily large and take an arbitrarily long time to collect.

3. Add callback parameter and change 'yield value' to 'callback(value)'.
+ Minor change to generator function.
- Minor to major change to caller to turn consumer code into a callback that somehow gets result of callback to where it is needed. (Avoiding the major changes sometimes needed was one of the motivations for generators.)

4. Combine caller and generator code by inlining one into or around the other.
+ Neither code will change much.
- Loss benefit of modularity and reuse without cut-and-paste, which is subject to error.

I have not thought through yet how well each of these work with recursive generators.

Conclusion:

Generators with yield make Python a great language for expressing combinatorial algorithms.

Terry Jan Reedy

--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to