3 # © Copyright 2021-2022, Scott Gasch
5 """A collection if :class:`Iterator` subclasses that can be composed
6 with another iterator and provide extra functionality. e.g.
8 + :class:`PeekingIterator`
9 + :class:`PushbackIterator`
10 + :class:`SamplingIterator`
15 from collections.abc import Iterator
16 from typing import Any, List, Optional
19 class PeekingIterator(Iterator):
20 """An iterator that lets you :meth:`peek` at the next item on deck.
21 Returns None when there is no next item (i.e. when
22 :meth:`__next__` will produce a StopIteration exception).
24 >>> p = PeekingIterator(iter(range(3)))
38 Traceback (most recent call last):
44 def __init__(self, source_iter: Iterator):
45 self.source_iter = source_iter
46 self.on_deck: List[Any] = []
48 def __iter__(self) -> Iterator:
51 def __next__(self) -> Any:
52 if len(self.on_deck) > 0:
53 return self.on_deck.pop()
55 item = self.source_iter.__next__()
58 def peek(self) -> Optional[Any]:
59 if len(self.on_deck) > 0:
60 return self.on_deck[0]
62 item = self.source_iter.__next__()
63 self.on_deck.append(item)
69 class PushbackIterator(Iterator):
70 """An iterator that allows you to push items back
71 onto the front of the sequence. e.g.
73 >>> i = PushbackIterator(iter(range(3)))
90 Traceback (most recent call last):
95 def __init__(self, source_iter: Iterator):
96 self.source_iter = source_iter
97 self.pushed_back: List[Any] = []
99 def __iter__(self) -> Iterator:
102 def __next__(self) -> Any:
103 if len(self.pushed_back) > 0:
104 return self.pushed_back.pop()
105 return self.source_iter.__next__()
107 def push_back(self, item: Any):
108 self.pushed_back.append(item)
111 class SamplingIterator(Iterator):
112 """An iterator that simply echoes what source_iter produces but also
113 collects a random sample (of size sample_size) of the stream that can
114 be queried at any time.
117 Until sample_size elements have been seen the sample will be
118 less than sample_size elements in length.
121 If sample_size is > len(source_iter) then it will produce a
124 >>> import collections
128 >>> s = SamplingIterator(iter(range(100)), 10)
138 >>> collections.deque(s)
139 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])
142 [78, 18, 47, 83, 93, 26, 25, 73, 94, 38]
146 def __init__(self, source_iter: Iterator, sample_size: int):
147 self.source_iter = source_iter
148 self.sample_size = sample_size
149 self.resovoir: List[Any] = []
150 self.stream_length_so_far = 0
152 def __iter__(self) -> Iterator:
155 def __next__(self) -> Any:
156 item = self.source_iter.__next__()
157 self.stream_length_so_far += 1
159 # Filling the resovoir
160 pop = len(self.resovoir)
161 if pop < self.sample_size:
162 self.resovoir.append(item)
163 if self.sample_size == (pop + 1): # just finished filling...
164 random.shuffle(self.resovoir)
166 # Swap this item for one in the resovoir with probabilty
167 # sample_size / stream_length_so_far. See:
169 # https://en.wikipedia.org/wiki/Reservoir_sampling
171 r = random.randint(0, self.stream_length_so_far)
172 if r < self.sample_size:
173 self.resovoir[r] = item
176 def get_sample(self) -> List[Any]:
180 if __name__ == '__main__':