what are generators?

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • castironpi@gmail.com

    what are generators?

    I'm looking for a cool trick using generators. Know any exercises I
    can work?
  • Miki

    #2
    Re: what are generators?

    On Mar 24, 8:17 am, castiro...@gmai l.com wrote:
    I'm looking for a cool trick using generators.  Know any exercises I
    can work?
    Simple one the comes to mind is flattening a list:
    >>list(flatte n([1, [[2], 3], [[[4]]]]))
    [1, 2, 3, 4]
    >>>
    HTH,
    --
    Miki <miki.tebeka@gm ail.com>
    If it won't be simple, it simply won't be. [Hire me, source code]

    Comment

    • castironpi@gmail.com

      #3
      Re: what are generators?

      On Mar 25, 7:36 pm, Miki <miki.teb...@gm ail.comwrote:
      On Mar 24, 8:17 am, castiro...@gmai l.com wrote:
      >
      I'm looking for a cool trick using generators.  Know any exercises I
      can work?
      >
      Simple one the comes to mind is flattening a list:
      >
      >list(flatten ([1, [[2], 3], [[[4]]]]))
      [1, 2, 3, 4]
      I don't think it's well-defined. (But this is impossible and useless
      calling.) CMIIW?

      This is generic:
      >>def f():
      ... __gen= None
      ... def g():
      ... i= 0
      ... while 1:
      ... i+= 1
      ... yield __gen( i )
      ... def set( gen ):
      ... nonlocal __gen
      ... __gen= gen
      ... return g, set
      ...
      >>a, set= f()
      >>b= a()
      >>set( lambda x: print( x ) )
      >>next( b )
      1
      >>next( b )
      2
      >>next( b )

      Comment

      • castironpi@gmail.com

        #4
        Re: what are generators?

        On Mar 27, 6:19 am, castiro...@gmai l.com wrote:
        On Mar 25, 7:36 pm, Miki <miki.teb...@gm ail.comwrote:
        >
        On Mar 24, 8:17 am, castiro...@gmai l.com wrote:
        >
        I'm looking for a cool trick using generators.  Know any exercises I
        can work?
        >
        Simple one the comes to mind is flattening a list:
        >
        >>list(flatte n([1, [[2], 3], [[[4]]]]))
        [1, 2, 3, 4]
        >
        I don't think it's well-defined.  (But this is impossible and useless
        calling.)  CMIIW?
        >
        This is generic:
        Revise:
        >>def f():
        ... __gen= None
        ... def set( gen ):
        ... nonlocal __gen
        ... __gen= gen
        ... yield set
        ... i= 0
        ... while 1:
        ... i+= 1
        ... yield __gen( i )
        ...
        >>a= f()
        >>set= next( a )
        >>set( lambda x: print( x ) )
        >>next( a )
        1
        >>next( a )
        2
        >>next( a )
        3
        >>>

        Comment

        Working...