Skip to content Skip to sidebar Skip to footer

Readable, Controllable Iterators?

I'm trying to craft an LL(1) parser for a deterministic context-free grammar. One of the things I'd like to be able to use, because it would enable much simpler, less greedy and mo

Solution 1:

Is there a clean, Pythonic, efficient way to control and change arbitrarily the iterator's current index?

No, there isn't. You could implement your own iterator type though; it wouldn't operate at the same speed (being implemented in Python), but it's doable. For example:

from collections.abc import Iterator

classSequenceIterator(Iterator):

    def__init__(self, seq):
        self.seq = seq
        self.idx = 0def__next__(self):
        try:
            ret = self.seq[self.idx]
        except IndexError:
            raise StopIteration
        else:
            self.idx += 1return ret

    defseek(self, offset):
        self.idx += offset

To use it, you'd do something like:

# Created outside for loop so you have name to call seek on
myseqiter = SequenceIterator(myseq)

for x in myseqiter:
    iftest(x):
        # do stuff with xelse:
        # Seek somehow, e.g.
        myseqiter.seek(1)  # Skips the next value

Adding behaviors like providing the index as well as value is left as an exercise.

Post a Comment for "Readable, Controllable Iterators?"