Skip to content

Instantly share code, notes, and snippets.

@jvkersch
Created May 21, 2020 07:27
Show Gist options
  • Save jvkersch/292d2e9cd0bdceb683a616fe37911480 to your computer and use it in GitHub Desktop.
Save jvkersch/292d2e9cd0bdceb683a616fe37911480 to your computer and use it in GitHub Desktop.
Prime sieve using generators (Python version of SICP 3.5.2)
""" 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