473,399 Members | 3,106 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,399 software developers and data experts.

An iterator with look-ahead

For use in a hand-coded parser I wrote the following simple
iterator with look-ahead. I haven't thought too deeply about what
peek ought to return when the iterator is exhausted. Suggestions
are respectfully requested. As it is, you can't be sure what a
peek() =None signifies until the next iteration unless you
don't expect None in your sequence.

Using itertools.tee is the alternative I thought about, but
caveates in the documentation disuaded me.

class LookAheadIter(object):
""" An iterator with the a peek() method, so you can see what's coming next.

If there is no look-ahead, peek() returns None.
>>nums = [1, 2, 3, 4, 5]
look = LookAheadIter(nums)
for a in look:
... print (a, look.peek())
(1, 2)
(2, 3)
(3, 4)
(4, 5)
(5, None)
"""
def __init__(self, data):
self.iter = iter(data)
self.look = self.iter.next()
self.exhausted = False
def __iter__(self):
return self
def peek(self):
if self.exhausted:
return None
else:
return self.look
def next(self):
item = self.look
try:
self.look = self.iter.next()
except StopIteration:
if self.exhausted:
raise
else:
self.exhausted = True
return item

--
Neil Cerutti
We've got to pause and ask ourselves: How much clean air do we really need?
--Lee Iacocca
Jan 10 '07 #1
5 2167
On 2007-01-10, Fredrik Lundh <fr*****@pythonware.comwrote:
if you're doing simple parsing on an iterable, it's easier and
more efficient to pass around the current token and the
iterator's next method:

http://online.effbot.org/2005_11_01_...imple-parser-1
Thank you. Much better.

--
Neil Cerutti
Jan 10 '07 #2
Neil Cerutti wrote:
For use in a hand-coded parser I wrote the following simple
iterator with look-ahead. I haven't thought too deeply about what
peek ought to return when the iterator is exhausted. Suggestions
are respectfully requested. As it is, you can't be sure what a
peek() =None signifies until the next iteration unless you
don't expect None in your sequence.
There is a different implementation in the Cookbook already:
http://aspn.activestate.com/ASPN/Coo.../Recipe/304373

George

Jan 10 '07 #3
Neil Cerutti wrote:
For use in a hand-coded parser I wrote the following simple
iterator with look-ahead.
There's a recipe for this:

http://aspn.activestate.com/ASPN/Coo.../Recipe/304373

Note that the recipe efficiently supports an arbitrary look-ahead, not
just a single item.
I haven't thought too deeply about what peek ought to return
when the iterator is exhausted. Suggestions are respectfully
requested.
In the recipe, StopIteration is still raised on a peek() operation that
tries to look past the end of the iterator.

STeVe
Jan 10 '07 #4
On 2007-01-10, Steven Bethard <st************@gmail.comwrote:
Neil Cerutti wrote:
>For use in a hand-coded parser I wrote the following simple
iterator with look-ahead.

There's a recipe for this:

http://aspn.activestate.com/ASPN/Coo.../Recipe/304373

Note that the recipe efficiently supports an arbitrary
look-ahead, not just a single item.
>I haven't thought too deeply about what peek ought to return
when the iterator is exhausted. Suggestions are respectfully
requested.

In the recipe, StopIteration is still raised on a peek()
operation that tries to look past the end of the iterator.
That was all I could think of as an alternative, but that makes
it fairly inconvenient to use. I guess another idea might be to
allow user to provide a "no peek" return value in the
constructor, if they so wish.

--
Neil Cerutti
Jan 10 '07 #5

Neil Cerutti wrote:
On 2007-01-10, Steven Bethard <st************@gmail.comwrote:
Neil Cerutti wrote:
For use in a hand-coded parser I wrote the following simple
iterator with look-ahead.
There's a recipe for this:

http://aspn.activestate.com/ASPN/Coo.../Recipe/304373

Note that the recipe efficiently supports an arbitrary
look-ahead, not just a single item.
I haven't thought too deeply about what peek ought to return
when the iterator is exhausted. Suggestions are respectfully
requested.
In the recipe, StopIteration is still raised on a peek()
operation that tries to look past the end of the iterator.

That was all I could think of as an alternative, but that makes
it fairly inconvenient to use. I guess another idea might be to
allow user to provide a "no peek" return value in the
constructor, if they so wish.

--
Neil Cerutti
You could raise a different Exception, PeekPastEndEception ?
- Paddy.

Jan 10 '07 #6

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

Similar topics

38
by: Grant Edwards | last post by:
In an interview at http://acmqueue.com/modules.php?name=Content&pa=showpage&pid=273 Alan Kay said something I really liked, and I think it applies equally well to Python as well as the languages...
6
by: greg | last post by:
Hello all, I havent used STL containers much, as I am used to MFC containers/classes always ..The differences that I could see is iterators and algorithms. The algorithms providing some basic...
3
by: John Smith | last post by:
Hey I have some code which I've been using on Microsoft VC++ for some time. Now I wanted to port my application to Mac OS X which offers gcc and the build fails. Here is the troublesome code:...
3
by: uclamathguy | last post by:
I am working on connected component analysis, but that is irrelevant. I have a mapping containing ints as the keys and sets of ints as the "values." Given an integer, I need to iterate through...
16
by: mailforpr | last post by:
How do I do that? The thing is, the only information I have about the iterator is the iterator itself. No container it is belonging to or anything. Like template<Iteratorvoid...
4
by: arnuld | last post by:
i wrote a programme to create a vector of 5 elements (0 to 4), here is the code & output: #include <iostream> #include <vector> int main() { std::vector<intivec; // dynamically create a...
6
by: antani | last post by:
VolumeType::ISetType::iterator findFirstIteratorMarked(const VolumeType::ISetType::iterator & it,const VolumeType::ISetType::iterator & e_it) { VolumeType::ISetType::iterator _it=it; while...
27
by: Steven D'Aprano | last post by:
I thought that an iterator was any object that follows the iterator protocol, that is, it has a next() method and an __iter__() method. But I'm having problems writing a class that acts as an...
1
by: Scott Gifford | last post by:
Hello, I'm working on an providing an iterator interface to a database. The basic thing I'm trying to accomplish is to have my iterator read rows from the database and return constructed...
5
by: Luis Zarrabeitia | last post by:
Hi there. For most use cases I think about, the iterator protocol is more than enough. However, on a few cases, I've needed some ugly hacks. Ex 1: a = iter() # assume you got the iterator...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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...
0
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...
0
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...

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.