Christoph Zwerschke wrote:[color=blue]
> dickinsm@gmail. com schrieb:[color=green]
>> How about:[/color][/color]
[color=blue][color=green]
>> [2]+[x for x in range(1,99) if 2**x%x==2][/color][/color]
[color=blue]
> If the range goes beyond 340, it also gives non-primes...[/color]
[2,3]+[x for x in range(1,99) if 2**x%x==2 and 3**x%x==3]
[2,3,5]+[x for x in range(1,99) if 2**x%x==2 and 3**x%x==3 and 5**x%x==5]
SCNR, Ralf
PS: They both break at 561, and further strengthening of the
condition will not help. Manual loop unrolling as follows works:
[2,3,... <insert all primes here>]+[x for x in range(1,99) if False]
For sufficiently small values of 99, this will also be a rather
short program.
While not nearly the shortest proposed thus far, I'm fond of:
from itertools import count, ifilter
def sieve(s=count(2 )):
while 1:p=s.next();s= ifilter(p.__rmo d__,s);yield p
It will generate quite a large number of primes before blowing up (at
least 50,000 primes, p=611,957) and it's much faster than the other
submissions thus far that can generate a more or less arbitrary number
of primes. It's still much slower than Alex Martelli's version in the
cookbook though.
[And yes I know that you can shave off one character by importing
ifilter as i, but that's too much ick for too little gain. There may
well be other, more fruitful ways to compact it though]
In the spirit of pointless pessimization and obfuscation I have crushed
something very similar to Alex Martelli's eratosthenes function onto a
single line. It's truly monstrous, but somewhat entertaining [Some
preemptive linebreaks added]:
def short():import itertools as it;D={};g=D.get ;return (
q for q in it.count(2) if
D.__setitem__(i t.dropwhile(D._ _contains__,
xrange(g(q,q)+q ,2**30,g(q,q))) .next(),g(q,q))
or q not in D and D.pop(q,1))
I'm sure there's a lesson to this somewhere. Something like I need to
find something better to do with my spare time.
Comment