Question

In python : Create an iterator design pattern whose instance would iterate over a generator. Here,...

In python : Create an iterator design pattern whose instance would iterate over a generator. Here, the generator function should display infinite multiples of 7. an iterator object that will use the pattern will display the 10 values of the multiples of 7 starting from 105.(using yield and next function)

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Here is the completed code for this problem. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. If not, PLEASE let me know before you rate, I’ll help you fix whatever issues. Thanks

Note: Please maintain proper code spacing (indentation), just copy the code part and paste it in your compiler/IDE directly, no modifications required.

#code

#an iterator class that iterates through a generator
class CustomIterator:
    #constructor taking a generator as parameter
    def __init__(self, generator):
        #assigning generator to instance variable
        self.__gen=generator

    def __iter__(self):
        #returns the iterator
        return self

    #returns the next element from generator if exists
    def __next__(self):
        #inside try-except block, calling and returning next() in gen object
        try:
            next_val=next(self.__gen)
            return next_val
        except:
            #in case of any exception, raising StopIteration flag
            raise StopIteration
#end of iterator class


#a generator function that returns infinite multiples of 7 starting with
#a given value (if provided, else uses 7 as start value)
def multiple_7_gen(start_value=7):
    #if start_value is not a multiple of 7, looping and incrementing start_value
    #continuously until start_value is a multiple of 7
    while start_value%7!=0:
        start_value+=1
    #now looping forever
    while True:
        #yielding start_value
        yield start_value
        #incrementing start_value by 7 for the next value
        start_value+=7
#end of multiple_7_gen method

#creating a CustomIterator object, passing a multiple_7_gen generator with start value=105
it=CustomIterator(multiple_7_gen(105))
#looping and printing first 10 multiples of 7 starting with 105
for i in range(10):
    print(next(it))

#output

105
112
119
126
133
140
147
154
161
168

Add a comment
Know the answer?
Add Answer to:
In python : Create an iterator design pattern whose instance would iterate over a generator. Here,...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • A) Please implement a Python script to define a student class with the following attributes (instance...

    A) Please implement a Python script to define a student class with the following attributes (instance attributes): cwid: student’s CWID first_name : student’s first name last_name: student’s last name gender: student’s gender gpa: student’s gpa Please make these attributes as private ones so they have to be accessed via getter/setter methods or property. For this purpose, please define a getter/setter method and property for each of the attributes. Another thing you need to do is to define a constructor that...

  • Python 3 Here is my question. In clock.py, define class Clock which will perform some simple...

    Python 3 Here is my question. In clock.py, define class Clock which will perform some simple time operations. Write an initializer function for Clock that will take three arguments from the user representing hour (in 24-hour format), minutes, and seconds. Each of these parameters should have a reasonable default value. You should check that the provided values are within the legal bounds for what they represent and raise a ValueError if they are not. if error_condition: raise ValueError("Descriptive error message")...

  • Design a program using Python and using from flask Import flask that generates a lottery number...

    Design a program using Python and using from flask Import flask that generates a lottery number but in a website.. The program should have an Integer array with 9 elements. Write a loop that steps through the array, randomly generating a number in the range of 0 through 42 for each element. (Use the random function) Then write another loop that displays the contents of the array. Each number should be displayed as a list, the numbers should be generated...

  • Using Python... Be sure to include the first line that makes the file an executable file...

    Using Python... Be sure to include the first line that makes the file an executable file in Linux. File Name: PyramidBlocks.py Python skills needed: Simple for loop (for var in range(num1,num2): Use of the range object Use of python math Creation of a Python Function Use of the print() method. Code Assignment 1: Alex sells pyramid wall art. In the design of his pyramids have each row has one more block than the last which means row 10 has 10...

  • python 3 inheritance Define a class named bidict (bidirectional dict) derived from the dict class; in...

    python 3 inheritance Define a class named bidict (bidirectional dict) derived from the dict class; in addition to being a regular dictionary (using inheritance), it also defines an auxiliary/attribute dictionary that uses the bidict’s values as keys, associated to a set of the bidict’s keys (the keys associated with that value). Remember that multiple keys can associate to the same value, which is why we use a set: since keys are hashable (hashable = immutable) we can store them in...

  • %%%%Python Question%%% Work from the template acrostic.py, which you can find on the ELMS page for...

    %%%%Python Question%%% Work from the template acrostic.py, which you can find on the ELMS page for this assignment. • In the Generator class, write an __init__() method with two parameters: self and the path to a text file containing one word per line. This method should read the words from the file, strip off leading and trailing whitespace, and store them in a dictionary where each key is a lower-case letter and each corresponding value is a list of words...

  • You may not add any instance variables to any class, though you may create local variables...

    You may not add any instance variables to any class, though you may create local variables inside of a method to accomplish its task. No other methods should be created other than the ones listed here.    Step 1 Develop the following class: Class Name: CollegeDegree Access Modifier: public Instance variables Name: major Access modifier: private Data type: String Name: numberOfCourses Access modifier: private Data type: int Name: courseNameArray Access modifier: private Data type: String [ ] Name: courseCreditArray Access...

  • You may not add any instance variables to any class, though you may create local variables...

    You may not add any instance variables to any class, though you may create local variables inside of a method to accomplish its task. No other methods should be created other than the ones listed here. (I need step 2 please.) Step 1 Develop the following class: Class Name: CollegeDegree Access Modifier: public Instance variables Name: major Access modifier: private Data type: String Name: numberOfCourses Access modifier: private Data type: int Name: courseNameArray Access modifier: private Data type: String [...

  • IN PYTHON Assignment Overview This assignment will give you experience on the use of classes. Understand...

    IN PYTHON Assignment Overview This assignment will give you experience on the use of classes. Understand the Application The assignment is to first create a class calledTripleString.TripleStringwill consist of threeinstance attribute strings as its basic data. It will also contain a few instance methods to support that data. Once defined, we will use it to instantiate TripleString objects that can be used in our main program. TripleString will contain three member strings as its main data: string1, string2, and string3....

  • This should be a python project.I need help with programming project in python. Here are the...

    This should be a python project.I need help with programming project in python. Here are the instructions: (75 points) Program runs successfully (10 points) Inputs weight from the user using a Scanner object. (5 points) Outputs all drink options in simple format (10 points) Inputs drink choices from the user using a Scanner object (5 points) Repeats until -1 is entered (45 points) Outputs the final summary correctly (25 points) Program contents follow readability standards including: (15 points) Correct use...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT