Skip to content

Instantly share code, notes, and snippets.

@curlup
Created June 12, 2012 21:53
Show Gist options
  • Save curlup/2920364 to your computer and use it in GitHub Desktop.
Save curlup/2920364 to your computer and use it in GitHub Desktop.
Eratosthenes
def filterer(k, DEBUG = False):
def g():
x = 1; m = yield;
while True:
m = yield (m if x<=k or x%k != 0 else 0)
x += 1
g = g()
g.next()
def _debug_filterer(x):
res = map(g.send, x)
print 'filterer({0})({1}) = {2}'.format(k, x, res)
return res
return _debug_filterer if DEBUG else lambda x: map(g.send, x)
ER = lambda N, DEBUG=False : filter(None, reduce(lambda s, f: f(s), (filterer(x, DEBUG) for x in range(2,1+N/2)), range(1,N+1)))
from itertools import *
def ifilterer(k, DEBUG = False):
def g():
x = 1; m = yield;
while True:
m = yield (m if x<=k or x%k != 0 else 0)
x += 1
g = g()
g.next()
def _debug_filterer(x):
res = imap(g.send, x)
print 'filterer({0})({1}) = {2}'.format(k, x, res)
return res
return _debug_filterer if DEBUG else lambda x: imap(g.send, x)
iER = lambda N, DEBUG=False: ifilter(None, reduce(lambda s, f: f(s), (ifilterer(x, DEBUG) for x in xrange(2,1+N/2)), xrange(1,N+1)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment