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] 2 2072
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
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] This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
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 = ...
|
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...
|
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...
|
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...
|
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...
| |
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...
|
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...
|
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. ...
|
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?
|
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,...
|
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...
| |
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...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
|
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,...
|
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...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
| |
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
| |