Skip to content

Commit 0592a5f

Browse files
committed
Added sliceable deque
1 parent e43a512 commit 0592a5f

1 file changed

Lines changed: 32 additions & 0 deletions

File tree

python_utils/containers.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -305,6 +305,38 @@ def __delitem__(
305305
super().__delitem__(index)
306306

307307

308+
class SlicableDeque(Generic[T], deque):
309+
def __getitem__(self, index: Union[int, slice]) -> Union[T, 'SlicableDeque[T]']:
310+
"""
311+
Return the item or slice at the given index.
312+
313+
>>> d = SlicableDeque[int]([1, 2, 3, 4, 5])
314+
>>> d[1:4]
315+
SlicableDeque([2, 3, 4])
316+
317+
>>> d = SlicableDeque[str](['a', 'b', 'c'])
318+
>>> d[-2:]
319+
SlicableDeque(['b', 'c'])
320+
321+
"""
322+
if isinstance(index, slice):
323+
start, stop, step = index.indices(len(self))
324+
return self.__class__(self[i] for i in range(start, stop, step))
325+
else:
326+
return super().__getitem__(index)
327+
328+
def pop(self) -> T:
329+
"""
330+
Remove and return the rightmost element.
331+
332+
>>> d = SlicableDeque[float]([1.5, 2.5, 3.5])
333+
>>> d.pop()
334+
3.5
335+
336+
"""
337+
return super().pop()
338+
339+
308340
if __name__ == '__main__':
309341
import doctest
310342

0 commit comments

Comments
 (0)