Add pushback iter.
[python_utils.git] / iter_utils.py
1 #!/usr/bin/env python3
2
3 import random
4 from collections.abc import Iterator
5 from typing import Any, List, Optional
6
7
8 class PeekingIterator(Iterator):
9     """An iterator that lets you peek() at the next item on deck.
10     Returns None when there is no next item (i.e. when __next__()
11     will produce a StopIteration exception).
12
13     >>> p = PeekingIterator(iter(range(3)))
14     >>> p.__next__()
15     0
16     >>> p.peek()
17     1
18     >>> p.peek()
19     1
20     >>> p.__next__()
21     1
22     >>> p.__next__()
23     2
24     >>> p.peek() == None
25     True
26     >>> p.__next__()
27     Traceback (most recent call last):
28       ...
29     StopIteration
30     """
31
32     def __init__(self, source_iter: Iterator):
33         self.source_iter = source_iter
34         self.on_deck: List[Any] = []
35
36     def __iter__(self) -> Iterator:
37         return self
38
39     def __next__(self) -> Any:
40         if len(self.on_deck) > 0:
41             return self.on_deck.pop()
42         else:
43             item = self.source_iter.__next__()
44             return item
45
46     def peek(self) -> Optional[Any]:
47         if len(self.on_deck) > 0:
48             return self.on_deck[0]
49         try:
50             item = self.source_iter.__next__()
51             self.on_deck.append(item)
52             return self.peek()
53         except StopIteration:
54             return None
55
56
57 class PushbackIterator(Iterator):
58     """An iterator that allows you to push items back
59     onto the front of the sequence.  e.g.
60
61     >>> i = PushbackIterator(iter(range(3)))
62     >>> i.__next__()
63     0
64     >>> i.push_back(99)
65     >>> i.push_back(98)
66     >>> i.__next__()
67     98
68     >>> i.__next__()
69     99
70     >>> i.__next__()
71     1
72     >>> i.__next__()
73     2
74     >>> i.push_back(100)
75     >>> i.__next__()
76     100
77     >>> i.__next__()
78     Traceback (most recent call last):
79       ...
80     StopIteration
81     """
82
83     def __init__(self, source_iter: Iterator):
84         self.source_iter = source_iter
85         self.pushed_back: List[Any] = []
86
87     def __iter__(self) -> Iterator:
88         return self
89
90     def __next__(self) -> Any:
91         if len(self.pushed_back):
92             return self.pushed_back.pop()
93         return self.source_iter.__next__()
94
95     def push_back(self, item: Any):
96         self.pushed_back.append(item)
97
98
99 class SamplingIterator(Iterator):
100     """An iterator that simply echoes what source_iter produces but also
101     collects a random sample (of size sample_size) of the stream that can
102     be queried at any time.
103
104     Note that until sample_size elements have been seen the sample will
105     be less than sample_size elements in length.
106
107     Note that if sample_size is > len(source_iter) then it will produce
108     a copy of source_iter.
109
110     >>> import collections
111     >>> import random
112
113     >>> random.seed(22)
114     >>> s = SamplingIterator(iter(range(100)), 10)
115     >>> s.__next__()
116     0
117
118     >>> s.__next__()
119     1
120
121     >>> s()
122     [0, 1]
123
124     >>> collections.deque(s)
125     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])
126
127     >>> s()
128     [78, 18, 47, 83, 93, 26, 25, 73, 94, 38]
129
130     """
131
132     def __init__(self, source_iter: Iterator, sample_size: int):
133         self.source_iter = source_iter
134         self.sample_size = sample_size
135         self.resovoir: List[Any] = []
136         self.stream_length_so_far = 0
137
138     def __iter__(self) -> Iterator:
139         return self
140
141     def __next__(self) -> Any:
142         item = self.source_iter.__next__()
143         self.stream_length_so_far += 1
144
145         # Filling the resovoir
146         pop = len(self.resovoir)
147         if pop < self.sample_size:
148             self.resovoir.append(item)
149             if self.sample_size == (pop + 1):  # just finished filling...
150                 random.shuffle(self.resovoir)
151
152         # Swap this item for one in the resovoir with probabilty
153         # sample_size / stream_length_so_far.  See:
154         #
155         # https://en.wikipedia.org/wiki/Reservoir_sampling
156         else:
157             r = random.randint(0, self.stream_length_so_far)
158             if r < self.sample_size:
159                 self.resovoir[r] = item
160         return item
161
162     def __call__(self) -> List[Any]:
163         return self.resovoir
164
165
166 if __name__ == '__main__':
167     import doctest
168
169     doctest.testmod()