Created
June 25, 2013 05:14
-
-
Save r3/5856093 to your computer and use it in GitHub Desktop.
Teaching generators
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
from math import sqrt | |
def count(start, step): | |
"""Happens to be included in the standard library""" | |
number = int(start) | |
while True: | |
yield number | |
start += number | |
def primes(start=2): | |
def is_prime(number): | |
if number == 1: | |
return False | |
if number == 2: | |
return True | |
if number % 2 == 0: | |
return False | |
maximum = int(sqrt(number)) + 1 | |
for divisor in range(3, maximum, 2): | |
if number % divisor == 0: | |
return False | |
return True | |
for potential_prime in count(start): | |
if is_prime(potential_prime): | |
yield potential_prime |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment