Http://anandology.com/python-practice-book/iterators.html
Problem 1: Write an iterator class reverse_iter
, which takes a list and iterates it from the reverse direction.::
>>>It=Reverse_iter([1,2,3,4])>>>it. Next()4>>> it. Next()3>>> it. Next()2>>> it. Next()1>>> it. Next()Traceback (most recent): File ' <stdin> ', line 1, in <module> Stopiteration
Wrote one, but realized, do not know whether the world's lowest efficiency.
Class Reverse_iter:
"" "DocString for ClassName" ""
def __init__ (Self,target):
self.current = 0
Self.target = target
Self.len = Len (target)
Print Self.len
Def next (self):
If Self.current < self.len:
Self.current+=1
return Self.target[self.len-self.current]
Else
Raise Stopiteration ()
def __iter__ (self):
return self
RI = Reverse_iter ([1,2,3,4])
Print Ri.next ()
Print Ri.next ()
Print Ri.next ()
Print Ri.next ()
Print Ri.next ()
"Python learning" iterator iterator little exercise