-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathprimesieve.py
More file actions
38 lines (31 loc) · 1.11 KB
/
primesieve.py
File metadata and controls
38 lines (31 loc) · 1.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# Let's try rendering the outline from
# http://en.literateprograms.org/Sieve_of_Eratosthenes_(Haskell)#Putting_it_together
# But I had to peek at their code for merge_all().
# (Could we make diff/merge shorter using Kragen's post on merging?)
# (Or how about defining diff in terms of merge and complement?)
def diff(xs, ys):
x, y = next(xs), next(ys)
while True:
if x < y: yield x
if x <= y: x = next(xs)
else: y = next(ys)
def merge(xs, ys):
x, y = next(xs), next(ys)
while True:
d = x - y
yield x if d <= 0 else y
if d <= 0: x = next(xs)
if 0 <= d: y = next(ys)
from itertools import count
from streams import LazyList
def gen_primes():
yield 2; yield 3; yield 5
multiples = merge_all(count(p*p, 2*p) for p in primes.tail())
for p in diff(count(7, 2), multiples): yield p
def merge_all(iters):
"Merge a stream of sorted streams, given map(next, iters) would be strictly increasing."
xs = next(iters)
yield next(xs)
for x in merge(xs, merge_all(iters)): yield x
primes = LazyList(gen_primes())
for p in primes: print(p)