Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 0f9da0a

Browse files
committed
Add a recursive Sieve of Eratosthenes prime generator. Not practical,
but it's a heck of a good generator exerciser (think about it <wink>).
1 parent 6ba5f79 commit 0f9da0a

1 file changed

Lines changed: 39 additions & 1 deletion

File tree

Lib/test/test_generators.py

Lines changed: 39 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -303,9 +303,47 @@
303303
[1, 2, 3]
304304
"""
305305

306+
# Fun tests (for sufficiently warped notions of "fun").
307+
308+
fun_tests = """
309+
310+
Build up to a recursive Sieve of Eratosthenes generator.
311+
312+
>>> def firstn(g, n):
313+
... return [g.next() for i in range(n)]
314+
315+
>>> def intsfrom(i):
316+
... while 1:
317+
... yield i
318+
... i += 1
319+
320+
>>> firstn(intsfrom(5), 7)
321+
[5, 6, 7, 8, 9, 10, 11]
322+
323+
>>> def exclude_multiples(n, ints):
324+
... for i in ints:
325+
... if i % n:
326+
... yield i
327+
328+
>>> firstn(exclude_multiples(3, intsfrom(1)), 6)
329+
[1, 2, 4, 5, 7, 8]
330+
331+
>>> def sieve(ints):
332+
... prime = ints.next()
333+
... yield prime
334+
... not_divisible_by_prime = exclude_multiples(prime, ints)
335+
... for p in sieve(not_divisible_by_prime):
336+
... yield p
337+
338+
>>> primes = sieve(intsfrom(2))
339+
>>> firstn(primes, 20)
340+
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71]
341+
"""
342+
306343
__test__ = {"tut": tutorial_tests,
307344
"pep": pep_tests,
308-
"zemail": email_tests}
345+
"email": email_tests,
346+
"fun": fun_tests}
309347

310348
# Magic test name that regrtest.py invokes *after* importing this module.
311349
# This worms around a bootstrap problem.

0 commit comments

Comments
 (0)