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
  • 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...

  • 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...

  • 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....

  • In this exam, you will design and implement a Python class called 'Date according to the...

    In this exam, you will design and implement a Python class called 'Date according to the following API specifications. • Do NOT use any existing classes in your answer such as datetime. . You will design your class so that it operates correctly on another planet, where the total days in a year, total days in a month, and months per year may be different. For our planet Earth, you will assume that a year has 360 days and all...

  • please there are some specific instructions on the question so i would greatly appreciate if they...

    please there are some specific instructions on the question so i would greatly appreciate if they are followed . thank you very much for your time This lab covers: arrays functions input exception handling Question 1 The purpose of this question is to write a python program (script) that manipulates arrays using vector arithmetic. You will compute the values of points The ellipse has a major axis whose length is a and a minor axis whose length is b. For...

  • You need not run Python programs on a computer in solving the following problems. Place your...

    You need not run Python programs on a computer in solving the following problems. Place your answers into separate "text" files using the names indicated on each problem. Please create your text files using the same text editor that you use for your .py files. Answer submitted in another file format such as .doc, .pages, .rtf, or.pdf will lose least one point per problem! [1] 3 points Use file math.txt What is the precise output from the following code? bar...

  • please use python and provide run result, thank you! click on pic to make it bigger...

    please use python and provide run result, thank you! click on pic to make it bigger For this assignment you will have to investigate the use of the Python random library's random generator function, random.randrange(stop), randrange produces a random integer in the range of 0 to stop-1. You will need to import random at the top of your program. You can find this in the text or using the online resources given in the lectures A Slot Machine Simulation Understand...

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
ADVERTISEMENT