how to convert a function into generator?

Carsten Haese carsten at uniqsys.com
Wed Dec 6 22:16:49 EST 2006


On Wed, 2006-12-06 at 17:33 +0100, Schüle Daniel wrote:
> def permute3gen(lst):
>      lenlst = len(lst)
>      def permute(perm, level):
>          if level == 1:
>              yield perm
>              return	# not sure return without a value is allowed, 
> theoretically it could be replaces with if/else block
>          for i in lst:
>              if i not in perm:
>                  permute(perm + (i,), level - 1)  ##1##
>      for item in lst:
>          yield permute((item,), lenlst) # makes generator from the outer 
> function too ##2##

Your only problem is in knowing what to do with recursively invoked
sub-generators. You have two such invocations, which I marked above with
##1## and ##2##, and neither one is handled correctly.

In ##1##, you construct a sub-generator and simply discard it. In ##2##,
you construct a sub-generator, and yield it (instead of yielding its
elements). In neither case do you actually consume any of the elements
that the sub-generators are prepared to produce.

To usefully invoke a sub-generator, you need to consume it (i.e. iterate
over it) and yield whatever it produces.

Hope this helps,

Carsten





More information about the Python-list mailing list