Recursive Generator Error?

David zhushenli at gmail.com
Sun Oct 21 20:40:41 EDT 2012


On Monday, October 22, 2012 7:59:53 AM UTC+8, Terry Reedy wrote:
> On 10/21/2012 7:29 PM, David wrote:
> 
> > I have a tree-like data structure, the basic elements are hash tables,
> 
> > and they are grouped into lists, like [[{'a':1},[{'b':2}]]].
> 
> > And I want to flat the lists and visit hash table one by one, like {'a':1}, {'b':2}.
> 
> > But my program didn't work as I wish. When it entered the 2nd
> 
> > flat_yield, it threw a GeneratorExit. Is there anything wrong?
> 
> 
> 
> 1. The Python version is not specified.
> 
> 2. You used 2.x; in 3.3 the code does exactly what I would expect, which 
> 
> is to say, nothing. No output, no error, no traceback ;-)
> 
> 3. The traceback is missing from this post.
> 
> 
> 
> > #- - - - - - - - - -
> 
> > def flat_yield(tbl_list):
> 
> >      for t in tbl_list:
> 
> >          if type(t) == type({}):
> 
> >              yield t
> 
> >          elif type(t) == type([]):
> 
> >              flat_yield(t)
> 
> 
> 
> 4. Think harder about what that expression does.
> 
> 
> 
> > a = [[{'a':1},[{'b':2}]]]
> 
> > for i in flat_yield(a):
> 
> >      print i
> 
> 
> 
> Hint: it calls flat_yield, which returns a generator, which is then 
> 
> discarded. You might have well written 'pass'.
> 
> 
> 
> Solution: use the recursively called generator and recursively yield 
> 
> what it yields. Replace 'flat_yield(t)' with
> 
> 
> 
>              for item in flat_yield(t):
> 
>                  yield item
> 
> 
> 
> and the output is what you want.
> 
> 
> 
> -- 
> 
> Terry Jan Reedy

Hi Terry, thank you! I use Python 2.7, and your solution works!

I have thought harder, still not very clear. 

If I have one "yield" in function, the function will become generator, and it can only be called in the form like "for item in function()" or "function.next()", and call the function directly will raise error, is it right?




More information about the Python-list mailing list