"Python learning" iterator iterator little exercise

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.