473,799 Members | 3,029 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Reuseable iterators - which is better?

In the tutorial there is an example iterator class that revesrses the
string given to the constructor. The problem is that this class works
only once, unlike built-in types like string. How to modify it that it
could work several times? I have tried two approaches. They both work,
but which of them is stylistically better?

class Reverse: #original one
"Iterator for looping over a sequence backwards"
def __init__(self, data):
self.data = data
self.index = len(data)
def __iter__(self):
return self
def next(self):
if self.index == 0:
raise StopIteration
self.index = self.index - 1
return self.data[self.index]

class Reverse: #1st approach
"Reuseable Iterator for looping over a sequence backwards"
def __init__(self, data):
self.data = data
self.index = len(data)
def __iter__(self):
return self
def next(self):
if self.index == 0:
self.index = len(self.data) #Reset when previous #
iterator goes out
raise StopIteration
self.index = self.index - 1
return self.data[self.index]

class Reverse: #2nd approach
"Reuseable Iterator for looping over a sequence backwards"
def __init__(self, data):
self.data = data
def __iter__(self):
self.index = len(self.data) #Reset as a part of iterator # creation
return self
def next(self):
if self.index == 0:
raise StopIteration
self.index = self.index - 1
return self.data[self.index]
Jun 23 '06 #1
2 2092
zefciu schrieb:
In the tutorial there is an example iterator class that revesrses the
string given to the constructor. The problem is that this class works
only once, unlike built-in types like string. How to modify it that it
could work several times? I have tried two approaches. They both work,
but which of them is stylistically better?

class Reverse: #original one
"Iterator for looping over a sequence backwards"
def __init__(self, data):
self.data = data
self.index = len(data)
def __iter__(self):
return self
def next(self):
if self.index == 0:
raise StopIteration
self.index = self.index - 1
return self.data[self.index]

class Reverse: #1st approach
"Reuseable Iterator for looping over a sequence backwards"
def __init__(self, data):
self.data = data
self.index = len(data)
def __iter__(self):
return self
def next(self):
if self.index == 0:
self.index = len(self.data) #Reset when previous #
iterator goes out
raise StopIteration
self.index = self.index - 1
return self.data[self.index]

class Reverse: #2nd approach
"Reuseable Iterator for looping over a sequence backwards"
def __init__(self, data):
self.data = data
def __iter__(self):
self.index = len(self.data) #Reset as a part of iterator # creation
return self
def next(self):
if self.index == 0:
raise StopIteration
self.index = self.index - 1
return self.data[self.index]


None. You don't reuse iterators! In the actualy example, reusage is
possible due to the whole data being known & available. But there might
be cases where this isn't possible - e.g. fetching data from a remote
location which is too large to fit into memory for re-iteration.

So generally speakiing, if you need an iterator, construct it.

Regards,

Diez
Jun 23 '06 #2
zefciu wrote:
In the tutorial there is an example iterator class that revesrses the
string given to the constructor. The problem is that this class works
only once, unlike built-in types like string. How to modify it that it
could work several times? I have tried two approaches. They both work,
but which of them is stylistically better?
Of the two posted below, I would much prefer the second one because iterators are not
meant to be reused (so they can be used on streams and similar as well). Therefore,
"resetting" an iterator by creating a new, similar one, is the natural way. Beware,
however, that your code does not actually create a new iterator and breaks if you want to
concurrently use more than one iterator of the same Reverse instance.
The "normal" way would be to have
def __iter__(self): return Reverse(self)
as a method of the sequence that is meant to be iterated over in reverse. Plus, of course,
everything but the __iter__ method from your second "reusable" iterator (which now isn't
reusable any more).
class Reverse: #original one
"Iterator for looping over a sequence backwards"
def __init__(self, data):
self.data = data
self.index = len(data)
def __iter__(self):
return self
def next(self):
if self.index == 0:
raise StopIteration
self.index = self.index - 1
return self.data[self.index]

class Reverse: #1st approach
"Reuseable Iterator for looping over a sequence backwards"
def __init__(self, data):
self.data = data
self.index = len(data)
def __iter__(self):
return self
def next(self):
if self.index == 0:
self.index = len(self.data) #Reset when previous #
iterator goes out
raise StopIteration
self.index = self.index - 1
return self.data[self.index]

class Reverse: #2nd approach
"Reuseable Iterator for looping over a sequence backwards"
def __init__(self, data):
self.data = data
def __iter__(self):
self.index = len(self.data) #Reset as a part of iterator # creation
return self
def next(self):
if self.index == 0:
raise StopIteration
self.index = self.index - 1
return self.data[self.index]

Jun 23 '06 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

24
3969
by: Lasse Vågsæther Karlsen | last post by:
I need to merge several sources of values into one stream of values. All of the sources are sorted already and I need to retrieve the values from them all in sorted order. In other words: s1 = s2 = s3 = for value in ???(s1, s2, s3):
14
2326
by: Jiri Kripac | last post by:
Languages such as Simula 67 contain a general concept of coroutines that allow the execution of a method to be suspended without rolling back the stack and then later resumed at the same place as it has been suspended. The C# iterators seem to be a special case of this general suspend/resume concept. The "yield" statement suspends the execution of the current method and calling MoveNext() resumes it. I think it would be cleaner to...
19
7556
by: John | last post by:
In STL's map implementation, the distance between two iterators it1, it2 takes O(K) to compute where K is the actual distance between the two iterators. In theory, a red black tree can do this in O(log K) time. Anyone knows if there is a way to do this in map<> or if map<> can be inherited/modified to do this? Thanks, --j
6
1853
by: Rennie deGraaf | last post by:
Hello, I would like to write a function that reads a sequence of unsigned shorts from /any/ container, converts them to pairs of unsigned chars, and writes them to /any/ container. In other words, something like this: That code works with the test driver provided. However, it /also/ compiles and executes if the input container holds something other than unsigned short or if the output container takes something other than
3
1547
by: Jess | last post by:
Hello, Iterators are typically put into five different categories, namely input iterator, output iterator, forward iterator, bidirectional iterator and random iterator. The differences come from the requirements each kind of iterator has to meet. Therefore, I think the five categories are kind of conceptual thing, i.e. they are not really C++ structs/classes etc, is this correct? There are some functions that return iterators. For...
9
2327
by: nottheartistinquestion | last post by:
As an intellectual exercise, I've implemented an STL-esque List<and List<>::Iterator. Now, I would like a signed distance between two iterators which corresponds to their relative position in the list. For instance, if I did something like distance(list.end(), list.begin()), I would get -list.size(). The STL's iterator distance function amounts to something like this: distance_type distance(Iterator first, Iterator last) {...
15
1931
by: =?UTF-8?B?RXJpayBXaWtzdHLDtm0=?= | last post by:
This is a little bit off topic but I hop you'll forgive me. A few days ago some expressed the opinion (in a post I can't find, but it was probably in one of Razii's threads) that Java's iterators were better than C++ iterators, or at least that the Java iterator concept was better (or something to that effect). I would be interested to hear about why whoever wrote it feels that way. -- Erik Wikström
7
2443
by: schickb | last post by:
I think it would be useful if iterators on sequences had the __index__ method so that they could be used to slice sequences. I was writing a class and wanted to return a list iterator to callers. I then wanted to let callers slice from an iterator's position, but that isn't supported without creating a custom iterator class. Are there reasons for not supporting this generally? I realize not all iterators would have the __index__ method,...
3
2756
by: zr | last post by:
Hi, Does usage of checked iterators and checked containers make code more secure? If so, can that code considered to be reasonably secure?
0
9685
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9538
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10249
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10219
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9068
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7563
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5461
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5584
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3755
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.