Generators/iterators, Pythonicity, and primes

John Posner jjposner at snet.net
Sun Apr 5 13:59:45 EDT 2009


 >> > g = (lambda primes = []:
 >> >         (n for n in count(2) if
 >> >             (lambda x, primes:
 >> >                 (primes.append(x) or True
 >> >                      if all(x%p for p in primes if p <= sqrt(x))
 >> >                      else False)
 >> >             )(n, primes)
 >> >         )
 >> >     )()
 >>
 >> This is of course much more accessible and doesn't even look weird.
 >>

Thanks! I think the only weirdness remaining is:

   primes.append(x) or True

... which is a trick to force a True value after primes.append(x) 
returns None.

BTW, for extra cleanliness, the parentheses can be omitted around lines 
4-7, the inner lambda expression.





More information about the Python-list mailing list