Filtered Iterator
Lesson 13 of 13 in Coddy's Python Iterators course.
Challenge
MediumCreate a PrimeNumberFilter class that implements a filtered iterator to generate prime numbers up to a specified limit. The class should have the following methods:
__init__(self, limit): Initialize the iterator with an upper limit.__iter__(self): Return the iterator object itself.__next__(self): Generate the next prime number or raise StopIteration when the limit is reached.
Implement a method is_prime(self, n) within the class to check if a number is prime.
After implementing the PrimeNumberFilter class, create an instance of it using the input value as the upper limit. Then, iterate through the prime numbers and print each number on a new line until the StopIteration exception is raised.
The following input will be provided:
- An integer representing the upper limit for generating prime numbers
Try it yourself
# Read input
limit = int(input())
class PrimeNumberFilter:
def __init__(self, limit):
self.limit = limit
self.current = 2
def __iter__(self):
return self
def __next__(self):
# TODO: Implement the __next__ method to generate the next prime number
pass
def is_prime(self, n):
# TODO: Implement the is_prime method to check if a number is prime
pass
# Create an instance of PrimeNumberFilter
prime_filter = PrimeNumberFilter(limit)
# TODO: Iterate through the prime numbers and print each one
# Remember to handle the StopIteration exception
# Note: Make sure to print each prime number on a new line