Generators/iterators, Pythonicity, and primes

Kay Schluehr kay.schluehr at gmx.net
Sun Apr 5 07:43:00 CEST 2009


> Question: Is there a way to implement this algorithm using generator
> expressions only -- no "yield" statements allowed?

Yes. Avoiding the yield statement is easy but one might eventually end
up with two statements because one has to produce a side effect on the
primes list. However we can use default parameters in lambdas and
finally get a single expression which is a generator expression:

g = (lambda primes = []:
      (n for n in count(2) \
         if
             (lambda n, primes: (n in primes if primes and n<=primes
[-1] \
         else
             (primes.append(n) or True \
                 if all(n%p for p in primes if p <= sqrt(n)) \
                 else False)))(n, primes)))()

assert g.next() == 2
assert g.next() == 3
assert g.next() == 5
assert g.next() == 7



More information about the Python-list mailing list