Chaining 501 generators breaks everything?
Jonathan Gardner
jgardner at jonathangardner.net
Fri Feb 19 16:47:46 EST 2010
On Fri, Feb 19, 2010 at 11:47 AM, Andrey Fedorov <anfedorov at gmail.com> wrote:
> I implemented a Sieve of Eratosthenes primes algorithm using generators:
>
> http://gist.github.com/309109
>
> This code which chains together 500 generators works fine (~1/20th of a
> second) on my laptop.
>
You may want a more traditional approach. Until Python gets tail
recursion (doubtful), this won't work very well on any platform.
#!/usr/bin/env python
from itertools import islice, count
from time import time
def primes():
seen = []
for i in count(2):
for s in seen:
if i%s == 0:
break
else: # Run if the for loop doesn't break
seen.append(i)
yield i
start = time()
for i in islice(primes(), 0, 10000):
print i
print time() - start
--
Jonathan Gardner
jgardner at jonathangardner.net
More information about the Python-list
mailing list