From 26a457920edc23d9f535c83843f42ca466aac6ce Mon Sep 17 00:00:00 2001 From: Jeremy Fincher Date: Tue, 29 Apr 2003 13:00:43 +0000 Subject: [PATCH] Added slice support to queue. --- src/structures.py | 38 ++++++++++++++++++++++++++------------ test/test_structures.py | 8 +++++--- 2 files changed, 31 insertions(+), 15 deletions(-) diff --git a/src/structures.py b/src/structures.py index a3709d4e6..0e6ada448 100644 --- a/src/structures.py +++ b/src/structures.py @@ -208,22 +208,36 @@ class queue(object): return 'queue([%s])' % ', '.join(map(repr, self)) def __getitem__(self, oidx): - (m, idx) = divmod(oidx, len(self)) - if m and m != -1: - raise IndexError, oidx - if len(self.front) > idx: - return self.front[-(idx+1)] + if type(oidx) == types.SliceType: + L = [] + for i in xrange(*sliceIndices(oidx, len(self))): + L.append(self[i]) + return L else: - return self.back[(idx-len(self.front))] + (m, idx) = divmod(oidx, len(self)) + if m and m != -1: + raise IndexError, oidx + if len(self.front) > idx: + return self.front[-(idx+1)] + else: + return self.back[(idx-len(self.front))] def __setitem__(self, oidx, value): - (m, idx) = divmod(oidx, len(self)) - if m and m != -1: - raise IndexError, oidx - if len(self.front) > idx: - self.front[-(idx+1)] = 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: - self.back[(idx-len(self.front))] = value + (m, idx) = divmod(oidx, len(self)) + if m and m != -1: + raise IndexError, oidx + if len(self.front) > idx: + self.front[-(idx+1)] = value + else: + self.back[(idx-len(self.front))] = value def __getstate__(self): return (list(self),) diff --git a/test/test_structures.py b/test/test_structures.py index f167f37f3..605264272 100644 --- a/test/test_structures.py +++ b/test/test_structures.py @@ -95,6 +95,8 @@ class RingBufferTestCase(unittest.TestCase): b.append(i) for i in range(len(b)): 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): L = range(10) @@ -182,8 +184,6 @@ class RingBufferTestCase(unittest.TestCase): b1 = RingBuffer(10, range(10)) self.failIf(b == b1) - - def testIter(self): b = RingBuffer(3, range(3)) L = [] @@ -208,9 +208,11 @@ class QueueTest(unittest.TestCase): self.assertEqual(q[i], i) for i in xrange(n, 0, -1): 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) - #self.assertEqual(q[3:7], queue([3, 4, 5, 6])) + self.assertEqual(q[3:7], queue([3, 4, 5, 6])) def testSetitem(self): q1 = queue()