Skip to content

Instantly share code, notes, and snippets.

@xuzhengfu
Last active August 1, 2020 15:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xuzhengfu/075c8121b1f1410e5fb4f4f3e0382e6c to your computer and use it in GitHub Desktop.
Save xuzhengfu/075c8121b1f1410e5fb4f4f3e0382e6c to your computer and use it in GitHub Desktop.
Zhengfu's assignment #2
from math import sqrt
from itertools import islice
def is_prime(num):
if num in (2, 3):
return True
for factor in range(2, int(sqrt(num)) + 1):
if num % factor == 0:
return False
return True
class prime_num_iterator:
"""An iterator that generates prime numbers."""
def __init__(self):
self.num = 1
def __iter__(self):
return self
def __next__(self):
while True:
self.num += 1
if is_prime(self.num):
return self.num
def prime_num_generator():
"""An generator that generates prime numbers."""
num = 2
while True:
if is_prime(num):
yield num
num += 1
if __name__ == "__main__":
primes_1 = prime_num_iterator()
primes_2 = prime_num_generator()
# Use the islice() method to slice off the first 10 prime numbers, of course, any number of primes is fine.
print(list(islice(primes_1, 0, 10)))
print(list(islice(primes_2, 0, 10)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment