The following needs to be coded in Python 3.5. You must have knowledge of genera
ID: 3822262 • Letter: T
Question
The following needs to be coded in Python 3.5. You must have knowledge of generators. Please answer with proper indentation, formatting, etc. Thanks!
Problem 2. Prime Number Generator Part a). Iterator Class Write a class called PrimeSeq that generates the sequence of the first n prime numbers, starting with 2, 3, 5,.... The class must comply with the iterator interface and must support the for statement. The next 0 method must return the next prime number from the sequence or throw Stoplteration if n primes have already been generated. This class should work like this: prints in order the first 100 prime numbers 2, 3, 5, prime seq PrimeSeq (100) for p in primeseq print (p)Explanation / Answer
# pastebin link for code: https://pastebin.com/HFcV2ueB
class PrimeSeq(object):
def __init__(self, n):
self._n = n
self._count = 0
self._last = 1
def __iter__(self):
return self
def _isPrime(self, n):
if n <= 1:
return False
if n <= 3:
return True
if n%2 == 0 or n%3 == 0:
return False
i = 5
while i*i <= n:
if n%i == 0 or n%(i+2) == 0:
return False
i = i + 6
return True
def _nextPrime(self):
n = self._last + 1
while not self._isPrime(n):
n = n+1
self._last = n
self._count += 1
return n
def __next__(self):
if self._count ==self._n:
raise StopIteration
else:
return self._nextPrime()
def prime_gen(n):
seq = PrimeSeq(n)
for p in seq:
yield p
primeseq = PrimeSeq(100)
for p in primeseq:
print(p)
prime_list = [p for p in PrimeSeq(100)]
print(prime_list)
for p in prime_gen(10):
print(p)
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.