[Tutor] Re: Request for code critique
Andrei
project5 at redrival.net
Wed Oct 22 14:34:51 EDT 2003
Andrei wrote:
> Matt Hehman wrote:
>
> for candidate in candidates:
> # find out if the candidate is indeed a prime
> limit = int(candidate ** 0.5)
> for prime in primes:
> if prime > limit:
> # we've found a new prime, go to next one
> primes.append(candidate)
> break
> elif candidate % prime == 0:
> # candidate is not a prime, go to next one
> break
>
> This does assume that you start out with primes containing at least [2,
> 3] and is 50% shorter than your solution (not counting comments). Bonus
> points if you can get that in a list comprehension :).
Just because I like torturing myself (don't ask), I ended up writing the
comprehension too:
[ primes.append(C) for C in candidates if not [1 for P in primes if not C%P ] ]
Much shorter, but I should point out that when running up to 100000000, the
comprehension is 30-50 times slower than the explicit for-loops :).
The while loop in Matt's code is ~3 times slower than the for-loops.
--
Yours,
Andrei
=====
Mail address in header catches spam. Real contact info (decode with rot13):
cebwrpg5 at bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur
yvfg, fb gurer'f ab arrq gb PP.
More information about the Tutor
mailing list