Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #58212

Re: "Backward"-Iterator - Beginners question

From Terry Reedy <tjreedy@udel.edu>
Subject Re: "Backward"-Iterator - Beginners question
Date 2013-10-31 18:35 -0400
References <5272CBA8.3070800@fam-goebel.de>
Newsgroups comp.lang.python
Message-ID <mailman.1893.1383258918.18130.python-list@python.org> (permalink)

Show all headers | View raw


On 10/31/2013 5:29 PM, Ulrich Goebel wrote:

> I'm locking for an "iterator" type with not only the .next() method, but
> with a .previous(), .first() and .last() method, so that I can through
> it from the beginning or from the end, and in both directions, even
> alternately (for example two steps forward, one backward, two steps
> forward).

You are free to write such a class, if it is appropriate for your actual 
use case.

If you have a concrete sequence object seq with random access, there is 
no reason to do so. First and last are seq[0] and seq[-1]. Given 
'cursor' i, prev and next are 'i-=1;seq[i]' and 'i+=1;seq[i]'.

There *are* virtual sequences where first and last are known or 
relatively easy to compute and for which prev and next are much easier 
to compute than a random nth item. Note that if you start with first and 
mostly move forward, prev might best be implemented using a list of 
items already seen. The list and the prev function might be limited to 
the last N items seen. It you give up the last function, the underlying 
sequence does not even have to have a definite end.

A somewhat realistic (useful) example might be the following. You have a 
very long sequence of bytes that represent utf-8 encoded characters. You 
want to view the sequence as a sequence of sentences. The sequence is 
too long to simply create a list of (decoded) sentences in memory.

-- 
Terry Jan Reedy

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: "Backward"-Iterator - Beginners question Terry Reedy <tjreedy@udel.edu> - 2013-10-31 18:35 -0400

csiph-web