Added slice support to queue.

This commit is contained in:
Jeremy Fincher 2003-04-29 13:00:43 +00:00
parent 71bd193c16
commit 26a457920e
2 changed files with 31 additions and 15 deletions

View File

@ -208,6 +208,12 @@ class queue(object):
return 'queue([%s])' % ', '.join(map(repr, self)) return 'queue([%s])' % ', '.join(map(repr, self))
def __getitem__(self, oidx): def __getitem__(self, oidx):
if type(oidx) == types.SliceType:
L = []
for i in xrange(*sliceIndices(oidx, len(self))):
L.append(self[i])
return L
else:
(m, idx) = divmod(oidx, len(self)) (m, idx) = divmod(oidx, len(self))
if m and m != -1: if m and m != -1:
raise IndexError, oidx raise IndexError, oidx
@ -217,6 +223,14 @@ class queue(object):
return self.back[(idx-len(self.front))] return self.back[(idx-len(self.front))]
def __setitem__(self, oidx, value): def __setitem__(self, oidx, value):
if type(oidx) == types.SliceType:
range = xrange(*sliceIndices(oidx, len(self)))
if len(range) != len(value):
raise ValueError, 'seq must be the same length as slice.'
else:
for (i, x) in zip(range, value):
self[i] = x
else:
(m, idx) = divmod(oidx, len(self)) (m, idx) = divmod(oidx, len(self))
if m and m != -1: if m and m != -1:
raise IndexError, oidx raise IndexError, oidx

View File

@ -95,6 +95,8 @@ class RingBufferTestCase(unittest.TestCase):
b.append(i) b.append(i)
for i in range(len(b)): for i in range(len(b)):
self.assertEqual(L[i], b[i]) self.assertEqual(L[i], b[i])
for i in range(len(b)):
self.assertEqual(list(b), list(b[:i]) + list(b[i:]))
def testSliceGetitem(self): def testSliceGetitem(self):
L = range(10) L = range(10)
@ -182,8 +184,6 @@ class RingBufferTestCase(unittest.TestCase):
b1 = RingBuffer(10, range(10)) b1 = RingBuffer(10, range(10))
self.failIf(b == b1) self.failIf(b == b1)
def testIter(self): def testIter(self):
b = RingBuffer(3, range(3)) b = RingBuffer(3, range(3))
L = [] L = []
@ -208,9 +208,11 @@ class QueueTest(unittest.TestCase):
self.assertEqual(q[i], i) self.assertEqual(q[i], i)
for i in xrange(n, 0, -1): for i in xrange(n, 0, -1):
self.assertEqual(q[-i], n-i) self.assertEqual(q[-i], n-i)
for i in xrange(len(q)):
self.assertEqual(list(q), list(q[:i]) + list(q[i:]))
self.assertRaises(IndexError, q.__getitem__, -(n+1)) self.assertRaises(IndexError, q.__getitem__, -(n+1))
self.assertRaises(IndexError, q.__getitem__, n) self.assertRaises(IndexError, q.__getitem__, n)
#self.assertEqual(q[3:7], queue([3, 4, 5, 6])) self.assertEqual(q[3:7], queue([3, 4, 5, 6]))
def testSetitem(self): def testSetitem(self):
q1 = queue() q1 = queue()