Created
May 21, 2020 07:27
-
-
Save jvkersch/292d2e9cd0bdceb683a616fe37911480 to your computer and use it in GitHub Desktop.
Prime sieve using generators (Python version of SICP 3.5.2)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" Infinite sieve of Eratosthenes using generators. | |
Python version of the Scheme code in SICP, paragraph 3.5.2. | |
""" | |
def primes(integers): | |
first = next(integers) | |
yield first | |
yield from primes(i for i in integers if i % first != 0) | |
def integers(start): | |
while True: | |
yield start | |
start += 1 | |
def take(stream, howmany): | |
return [next(stream) for _ in range(howmany)] | |
ps = primes(integers(2)) | |
print(take(ps, 100)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment