Generators/iterators, Pythonicity, and primes

Kay Schluehr kay.schluehr at
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) \
             (lambda n, primes: (n in primes if primes and n<=primes
[-1] \
             (primes.append(n) or True \
                 if all(n%p for p in primes if p <= sqrt(n)) \
                 else False)))(n, primes)))()

assert == 2
assert == 3
assert == 5
assert == 7

More information about the Python-list mailing list