I've been assigned the following Python homework:
Implement myrange that acts like
rangeusing iterators. Define a functionmyrangeand define a classMyRange.
We've just seen iterators, so I think I'm asked to use them. I am not required to write a sophisticated code, but only something that allows the range-for loop syntax.
Professor said that, roughly, an iterator is an object for which the dunder method __next__ is provided. I've seen there are similar questions here. However, none of them is defining the __next__ method in a class.
So, here's what I did: first I implemented MyRange class and then my range. After that, I did two tests.
Question: It works, but I'd like to be sure from you if I solved correctly the question, I mean, if this is what I was supposed to do :-) As I said, I've just seen what is an iterator.
class MyRange():
def __init__(self,data):
self.data = data
self.check()
self.index = -1
def check(self):
assert len(self.data)>0, "Not enough data"
def __iter__(self):
return self
def __next__(self):
if self.index == len(self.data)-1:
raise StopIteration
self.index= self.index+1
return self.data[self.index]
def my_range(*args):
return MyRange((args))
print("Tests using MyRange class \n")
for i in MyRange((1,2,3,4)):
print(i)
print("Tests with range for loop \n")
for i in my_range(1,2,3,4,5,"Hello"):
print(i)
r = MyRange((1,2,3,4,"Last Value"))
print(next(r))
print(next(r))
print(next(r))
print(next(r))
print(next(r))
print(next(r))
I'll show here the output, which seems the correct one:
1
2
3
4
Tests with range for loop
1
2
3
4
5
Hello
1
2
3
4
Last Value
Traceback (most recent call last):
File "Untitled3.py", line 45, in <module>
print(next(r)) #<-- Raises StopIteration
File "Untitled3.py", line 16, in __next__
raise StopIteration
StopIteration
myrange()is supposed to act likerange(), shouldn't it take similar arguments:start,stop, andstep? It doesn't seem like your implementation is following the instructions, but you obviously have more context than I do. A range is a device to generate integers (integers often used to index into a data collection), but you have implementedmyrange()to take the data collection itself as an argument. Perhaps you can edit your question to clarify. \$\endgroup\$__next__in our class. I think I can fix this point. For the moment, assuming that the classMyRangeis correct, do you think thatmy_rangeis implemented correctly? \$\endgroup\$rangetwo different ways (1) as a function (e.g. usingyieldin a loop), and (2) as a class (e.g. having__iter__and__next__methods). \$\endgroup\$MyRangeandmy_range()are incorrect. You have successfully implemented an iterable object (MyRange), but it is not an iterable object that behaves at all likerange(). \$\endgroup\$