#!/usr/bin/env python3
+# © Copyright 2021-2022, Scott Gasch
+
+"""A collection if :class:`Iterator` subclasses that can be composed
+with another iterator and provide extra functionality. e.g.
+
+ + :class:`PeekingIterator`
+ + :class:`PushbackIterator`
+ + :class:`SamplingIterator`
+
+"""
+
import random
from collections.abc import Iterator
from typing import Any, List, Optional
class PeekingIterator(Iterator):
- """An iterator that lets you peek() at the next item on deck.
- Returns None when there is no next item (i.e. when __next__()
- will produce a StopIteration exception).
+ """An iterator that lets you :meth:`peek` at the next item on deck.
+ Returns None when there is no next item (i.e. when
+ :meth:`__next__` will produce a StopIteration exception).
>>> p = PeekingIterator(iter(range(3)))
>>> p.__next__()
Traceback (most recent call last):
...
StopIteration
+
"""
def __init__(self, source_iter: Iterator):
return self
def __next__(self) -> Any:
- if len(self.pushed_back):
+ if len(self.pushed_back) > 0:
return self.pushed_back.pop()
return self.source_iter.__next__()
collects a random sample (of size sample_size) of the stream that can
be queried at any time.
- Note that until sample_size elements have been seen the sample will
- be less than sample_size elements in length.
+ .. note::
+ Until sample_size elements have been seen the sample will be
+ less than sample_size elements in length.
- Note that if sample_size is > len(source_iter) then it will produce
- a copy of source_iter.
+ .. note::
+ If sample_size is > len(source_iter) then it will produce a
+ copy of source_iter.
>>> import collections
>>> import random
>>> s.__next__()
1
- >>> s()
+ >>> s.get_sample()
[0, 1]
>>> collections.deque(s)
deque([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, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99])
- >>> s()
+ >>> s.get_sample()
[78, 18, 47, 83, 93, 26, 25, 73, 94, 38]
"""
self.resovoir[r] = item
return item
- def __call__(self) -> List[Any]:
+ def get_sample(self) -> List[Any]:
return self.resovoir