Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

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

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__() method must return the next prime number from the sequence or throw StopIteration if n primes have already been generated.

This class should work like this:

# prints in order the first 100 prime numbers: 2,3,5,... 

primeseq = PrimeSeq(100)

for p in primeseq: print(p)

yield

Extra credit part, for 5 points:

# Create a list with the first 100 prime numbers: 

primes_lst = [p for p in PrimeSeq(100)] print(primes_lst)

A PrimeSeq object must use an instance attribute list self.__primes that accumulates all prime numbers computed until the most recent call to __next__(). Use that to speed up the computation of the next prime number from the sequence by checking divisibility for a number p only with prime divisors <= sqrt(p).

Part b). Generator

Write a Python generator called prime_gen(n) that takes an integer n >= 0 and produces the sequence of the first n prime numbers. This generator is defined as a function that uses the keyword to output a value, as seen on the Chapter 16 lecture PDF file, on slides 60-70. This generator produces the same number sequence as the PrimeSeq class from part a). Here is how it can be used in a for loop to print the first 10 prime numbers:

for p in prime_gen(10): print(p)

Write the code from parts a) and b) in a file p2.py.

Add in this file a function called main() that demonstrates both the PrimeSeq class and the prime_gen() generator by creating and printing lists with the first 100 prime numbers.

in python

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Database Principles Programming And Performance

Authors: Patrick O'Neil, Elizabeth O'Neil

2nd Edition

1558605800, 978-1558605800

More Books

Students also viewed these Databases questions

Question

b. The number of unemployed workers increases.

Answered: 1 week ago

Question

5. Have you ever maintained a blog?

Answered: 1 week ago