Skip to content

Instantly share code, notes, and snippets.

@Xuzhengfu Xuzhengfu/

Last active Aug 1, 2020
What would you like to do?
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
You can’t perform that action at this time.