Iterators and generators · 14 / 15 Exercise Medium

Custom range

Objective

Create a Python program with an iterator class: an object that can be looped over with for because it implements __iter__ and __next__.

Instructions

  • Define the class MyRange with __init__(self, start, end, step), which stores the three values and an attribute current = start.
  • __iter__ returns self. __next__ raises StopIteration if current >= end; otherwise, it stores the current value, adds step to current and returns the stored value.
  • Read a line with three integers: start end step (with a positive step and at least one value in the range). Store the values with list(MyRange(start, end, step)).
  • Show the values on one line and, on the next one, Count: K.
Input
0 10 2
Output
0 2 4 6 8
Count: 5

Open the editor in full screen: the statement on the left and your code, the output and the tests on the right.

Start exercise