473,587 Members | 2,505 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Using and Implementing iterators with classes such as linked lists

I am taking a second programming course in Java and am currently
attempting to apply what I have learned using Python instead. One
thing that is puzzling me is how to use an iterator.

I am writing a module containing everything I'd need for canonical
linked lists. One particularly useful feature would be to use a for
loop over the whole structure. For this I have learned the benefits
of
iterators. I have read a few book entries on Python iterators, as
well
as an online article by David Mertz, I believe, and PEP 234, and I
may
be lacking some insight but I am still confused about one thing. How
does the iteration know where to begin?

AFAIU, in my LinkedList class, I can either have the LinkedList be
its
own iterator by making its __iter__() method return self and defining
a next() method, or I can have a separate iterator called from
LinkedList's __iter__(). My view is that it would be best to have the
LinkedList be its own iterator - is that the case? Or is an external
iterator preferable in this case?

My problem with implementing the former comes with this: in
LinkedList
I would have:

....

def __init__(self):
return self

....

def next(self):
if self.__current. next == None:
raise StopIteration
self.__current = self.__current. next
return self.__current. next

....

Now, is this good in the eyes of more experienced programmers? Also,
do I really want to dedicate an instance variable to keep track of
where to begin iteration (if __current is used for other purposes,
iteration could conceivably begin anywhere right?)? Does this suggest
that I should have a separate LinkedListItera tor class? And if I do
have that separate class, do I make the LinkedList.__it er__() pass on
to LinkedListItera tor's constructor the head node of LinkedList, or
the whole linked list?

Thanks in advance,

Jeremy

_______________ _______________ ____
Do you Yahoo!?
Free Pop-Up Blocker - Get it now
http://companion.yahoo.com/

Jul 18 '05 #1
3 5615
Adelein and Jeremy <ad************ **@yahoo.com> wrote in
news:ma******** *************** **************@ python.org:
AFAIU, in my LinkedList class, I can either have the LinkedList be
its
own iterator by making its __iter__() method return self and defining
a next() method, or I can have a separate iterator called from
LinkedList's __iter__(). My view is that it would be best to have the
LinkedList be its own iterator - is that the case? Or is an external
iterator preferable in this case?


It sounds a very bad idea to have LinkedList be its own iterator. If you
did that then you could only have one iteration over each list at a time.
In practical use, you will find that you want to iterate over a list, and
you don't know or care whether another piece of code is already iterating
over the same list.

The easiest way to handle it here is to use a generator to do the actual
iteration:

def __iter__(self):
def iterate(current ):
while current.next is not None:
next = current.next
yield current
current = next
return iterate(self)
--
Duncan Booth du****@rcp.co.u k
int month(char *p){return(1248 64/((p[0]+p[1]-p[2]&0x1f)+1)%12 )["\5\x8\3"
"\6\7\xb\1\x9\x a\2\0\4"];} // Who said my code was obscure?
Jul 18 '05 #2
In article <Xn************ **************@ 127.0.0.1>,
Duncan Booth <du****@rcp.co. uk> wrote:

def __iter__(self):
def iterate(current ):
while current.next is not None:
next = current.next
yield current
current = next
return iterate(self)


Huh? Why the extra function and complexity?

def __iter__(self):
current = self
while current is not None:
yield current
current = current.next
--
Aahz (aa**@pythoncra ft.com) <*> http://www.pythoncraft.com/

Weinberg's Second Law: If builders built buildings the way programmers wrote
programs, then the first woodpecker that came along would destroy civilization.
Jul 18 '05 #3
aa**@pythoncraf t.com (Aahz) wrote in news:bq******** **@panix3.panix .com:
In article <Xn************ **************@ 127.0.0.1>,
Duncan Booth <du****@rcp.co. uk> wrote:

def __iter__(self):
def iterate(current ):
while current.next is not None:
next = current.next
yield current
current = next
return iterate(self)


Huh? Why the extra function and complexity?

def __iter__(self):
current = self
while current is not None:
yield current
current = current.next


Because I was asleep.

--
Duncan Booth du****@rcp.co.u k
int month(char *p){return(1248 64/((p[0]+p[1]-p[2]&0x1f)+1)%12 )["\5\x8\3"
"\6\7\xb\1\x9\x a\2\0\4"];} // Who said my code was obscure?
Jul 18 '05 #4

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

Similar topics

1
1738
by: adeleinandjeremy | last post by:
I am taking a second programming course in Java and am currently attempting to apply what I have learned using Python instead. One thing that is puzzling me is how to use an iterator. I am writing a module containing everything I'd need for canonical linked lists. One particularly useful feature would be to use a for loop over the whole...
7
4597
by: sks_cpp | last post by:
Consider the following: list<int> a; // assume a contains some number of integers list<int>::iterator iter = a.find(10); for (iter; iter < a.end(); ++iter) { std::cout << "found one\n"; } ================
0
312
by: D.C.Dunn | last post by:
Please forgive the naivety of my following question. I'm new to C++, and am trying to get to grips with OOP. My question concerns iterators and derived classes. Please note that I don't want to use the STL, just get my head round how to do this from scratch. I have (at least) two classes derived from an abstract base class, and I want to...
3
3261
by: s_subbarayan | last post by:
Dear all, 1)In one of our implementation for an application we are supposed to collate two linked lists.The actual problem is like this: There are two singularly linked lists, the final output will be a "perfectly shuffle" of the lists together into a single list. The new list should consist of consecutively alternating nodes from both...
11
3753
by: efrat | last post by:
Hello, I'm planning to use Python in order to teach a DSA (data structures and algorithms) course in an academic institute. If you could help out with the following questions, I'd sure appreciate it: 1. What exactly is a Python list? If one writes a, then is the complexity Theta(n)? If this is O(1), then why was the name "list" chosen? If...
9
7820
by: raylopez99 | last post by:
What's the best way of implementing a multi-node tree in C++? What I'm trying to do is traverse a tree of possible chess moves given an intial position (at the root of the tree). Since every chess position has around 30 moves, it would mean every node of the tree would have 30 branches (on average), which in turn themselves would average...
1
1492
by: sk.rasheedfarhan | last post by:
Hi , I am using C# I am having 4 classes. like below. public class A { String m_strRuleName; String m_strRuleGuid; // Some member functions. public Object NextItem; }
10
6564
by: AZRebelCowgirl73 | last post by:
This is what I have so far: My program! import java.util.*; import java.lang.*; import java.io.*; import ch06.lists.*; public class UIandDB {
9
2314
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...
0
7923
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...
0
8216
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
8349
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...
0
8221
tracyyun
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6629
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...
0
5395
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 then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3845
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...
0
3882
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1455
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.