2.2 features

Tom Good Tom_Good1 at excite.com
Wed Jul 25 17:40:08 EDT 2001


Jeff Shannon <jeff at ccvcorp.com> wrote in message news:<3B5F0867.7447E5FB at ccvcorp.com>...
> Tom Good wrote:
> 
> > "Nick Perkins" <nperkins7 at home.com> wrote in message
>  
> >
> > > How about generators, who's tried them out?
> >
> > [snip]
> >
> > I like generators a lot.  Here's a fun one:
> >
> > #------ begin code
> > [snip]
> > if __name__ == "__main__":
> >     g = fib()
> >     for i in range(9):
> >         print g.next(),
> >
> > #------ end code
> 
> Haven't looked into this in detail, or even downloaded 2.2 yet, but...
> 
> couldn't that be written as:
> 
> if __name__ == '__main__':
>     for i in fib():
>         print i,
> 
> ???
> 
> (being under the impression that the main point of iterators is convenient for-loop usage...)
> 
> Jeff Shannon
> Technician/Programmer
> Credit International

The problem with using "for i in fib():" is that fib() will generate
an infinite set!  Infinite sets are fun to work with, but somewhat
problematic to output :-)

The example uses "for i in range(9):" instead, in order to generate
and show only the first few Fibonacci numbers.

Which reminds me, when working with unbounded generators, you can wrap
them with another generator to restrict their output, with something
like this:

#------ begin code

def genWhile(g, condition):
    """
    run generator g while 'condition' is true.
    Condition is a partial expression string such as "< 10"
    to be evaluated with g.next() as the left side
    """
    while 1:
        next = g.next()
        if eval("next " + condition):
            yield next
        else:
            raise StopIteration

#------ end code

Then you can say, for example:

>>> g = fib()
>>> [x for x in genWhile(g, "< 50")]

[1, 1, 2, 3, 5, 8, 13, 21, 34]

...to get the Fibonacci numbers that are less than 50.



Tom



More information about the Python-list mailing list