Yield

Carsten Haese carsten at uniqsys.com
Thu Nov 16 11:24:35 EST 2006


On Thu, 2006-11-16 at 08:09 -0800, Danny Colligan wrote:
> > The more trivial the example, the harder it is to see the advantage.
> 
> I absoultely agree.  Thanks for pointing me out to some real-world
> code.  However, the function you pointed me to is not a generator
> (there is no yield statement... it just returns the entire list of
> primes).  A generator version would be:
> 
> >>> def primes(n):
> ...     if n<2: yield []
> ...     s=range(3,n+1,2)
> ...     mroot = n ** 0.5
> ...     half=(n+1)/2-1
> ...     i=0
> ...     m=3
> ...     while m <= mroot:
> ...         if s[i]:
> ...             j=(m*m-3)/2
> ...             s[j]=0
> ...             while j<half:
> ...                 s[j]=0
> ...                 j+=m
> ...         i=i+1
> ...         m=2*i+3
> ...     yield 2
> ...     for x in s:
> ...         if x: yield x

Not quite:
>>> x = primes(1)
>>> x.next()
[]
>>> x.next()
2
>>> x.next()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
StopIteration

To handle n<2 correctly, you have to "return" instead of "yield []".

>>> x = primes(1)
>>> x.next()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
StopIteration

-Carsten





More information about the Python-list mailing list