Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Consider the following program. class ny_lte r: def _lnlt_(self, max, aultlpller

ID: 3836228 • Letter: C

Question

Consider the following program. class ny_lte r: def _lnlt_(self, max, aultlpller): self.current - 0 seir.nax - max seir.aultlpller - multiplier def___ iter_(self): return self def _next_(self): If self .current > - self.max: raise Stoplteratlon self.current r- 1 return self.current * self.multiplier def rcgular_func(lnt__llst, an_lnt): res - [] for 1 in int_list: res.append(1 * an_int) return res def generator_func(int_list, an_int; for 1 in int_list: yield 1 + an_int. x = reguloar_func([1, 2, 3], 5) y = generator_func([1, 2, 3], 5) print ("x - []". format (x)) print ("y - ()" format (y)) for 1 in range (10): try: print ("next y - []". format (next yy)) except StopIteration: print ("stopped at []". format (i)) break d - my_iter (3, 5) for 1 in d: print (" next d []". format (1)) (b) What output will the above program produce? (c) What is the significance of the___ next__ method in the context a for loop that uses an instance (such as d above)? What is the significance of the StopIteration exoeption?

Explanation / Answer

b) The output of the above rogram is :

x = [5, 10, 15]
y = <generator object generator_func at 0x0000029C63D42938>
next y = 5
next y = 10
next y = 15
stopped at 3
next d 5
next d 10
next d 15
next d 20

c) A generator function is a special kind of iterator; it indeed raises StopIteration when the function is done . It is a requirement of iterators; they must raise StopIteration when they are done; in fact, once a StopIteration has been raised, attempting to get another element from them must always raise StopIteration again.

The next method is multiplying the value with the current value i.e in each and every iteration the current values is getting changed and it is being multiplied by max till the time current is less than or equal to max when it reaches that level it will raise 'StopIteration' .

__next__ is a special method that exist in iterator/generator protocol in this example it is using current and max values.