The basic iterator for a list is a very "fast-but-dumb" design. It doesn't allow one to skip forward (except with "continue"), or backward (at all), nor does it behave well if the list is modified while it is being traversed. The following is NOT the be-all and end-all of improved iterators, but it gives a few ideas of how a better one might be created.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 | class MovableListIterator:
"""This is an iterator for lists which allows one to advance
or regress the position in the list. It also will raise an
exception if the list is lengthened or shortened."""
def __init__(self, myList):
self.myList = myList
self.originalLength = len(myList)
self.nextIndex = 0
def __iter__(self):
return self
class ListModifiedException(Exception):
pass
def next(self):
if len(self.myList) != self.originalLength:
raise MovableListIterator.ListModifiedException
index = self.nextIndex
if index >= self.originalLength:
raise StopIteration
self.nextIndex += 1
return self.myList[index]
def advance(self, places=1):
self.nextIndex += places
def regress(self, places=1):
self.nextIndex -= places
import unittest
class TestMovableListIterator(unittest.TestCase):
def test_create(self):
li = list('abcde')
i = MovableListIterator(li)
def test_basic_loop(self):
li = 'abcde'
self.assertEqual( list(li), [x for x in MovableListIterator(li)] )
def test_advance(self):
li = 'abcdef'
result = []
i = MovableListIterator(li)
result.append( i.next() )
i.advance()
result.append( i.next() )
i.advance(2)
result.append( i.next() )
self.assertEqual( list('acf'), result )
self.assertRaises( StopIteration, i.next )
def test_regress(self):
li = 'abc'
result = []
i = MovableListIterator(li)
result.append( i.next() )
i.regress()
result.append( i.next() )
result.append( i.next() )
result.append( i.next() )
i.regress(2)
result.append( i.next() )
result.append( i.next() )
self.assertEqual( list('aabcbc'), result )
self.assertRaises( StopIteration, i.next )
def test_shrink_throws(self):
li = [1,2,3,4]
i = MovableListIterator(li)
li.pop()
self.assertRaises( MovableListIterator.ListModifiedException,
i.next )
def test_grow_throws(self):
li = [1,2,3,4]
i = MovableListIterator(li)
li.append(5)
self.assertRaises( MovableListIterator.ListModifiedException,
i.next )
|
Tags: algorithms