Last active
June 6, 2021 18:29
-
-
Save realeroberto/41d787b2a80068d29cff to your computer and use it in GitHub Desktop.
A simple Python iterator that returns the sequence of prime numbers on successive calls to its next() method...
This file contains hidden or 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
class PrimeGenerator: | |
def __init__(self): | |
self.primes = [] | |
self.current_prime = 1 | |
def __iter__(self): | |
return self | |
def __next__(self) -> int: | |
candidate = self.current_prime + 1 | |
while True: | |
is_prime = True | |
for prime in self.primes: | |
if candidate % prime == 0: | |
is_prime = False | |
break | |
if is_prime: | |
self.primes.append(candidate) | |
self.current_prime = candidate | |
break | |
else: | |
candidate += 1 | |
return self.current_prime |
Thank you @Myzel394, great contribution!
My suggestion:
- use else clauses on loops
- early stop: no need to look beyond the square root of the candidate
class PrimeGenerator:
def __init__(self):
self.primes = []
self.current = 1
def __iter__(self):
return self
def __next__(self) -> int:
candidate = self.current + 1
while True:
for prime in itertools.takewhile(lambda p: candidate >= p**2, self.primes):
if candidate % prime == 0:
break
else:
self.primes.append(candidate)
self.current = candidate
break
candidate += 1
return self.current
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I would rewrite it this way (Best practises; iterator instead of calling
.next()
):