X-Git-Url: https://wannabe.guru.org/gitweb/?a=blobdiff_plain;f=iter_utils.py;h=69f58226aada7b718f6e938e2d635a74fea5ba53;hb=562a15c6397610cf93646d9530005eb4a0d6e6f8;hp=00c4221b26201d7c0a3a1b5bfee938d00371d914;hpb=1172b6778a036431b542fdc89bbfdd13e13b5e8d;p=python_utils.git diff --git a/iter_utils.py b/iter_utils.py index 00c4221..69f5822 100644 --- a/iter_utils.py +++ b/iter_utils.py @@ -1,12 +1,25 @@ #!/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. + """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). >>> p = PeekingIterator(iter(range(3))) >>> p.__next__() @@ -25,6 +38,7 @@ class PeekingIterator(Iterator): Traceback (most recent call last): ... StopIteration + """ def __init__(self, source_iter: Iterator): @@ -52,11 +66,61 @@ class PeekingIterator(Iterator): return None +class PushbackIterator(Iterator): + """An iterator that allows you to push items back + onto the front of the sequence. e.g. + + >>> i = PushbackIterator(iter(range(3))) + >>> i.__next__() + 0 + >>> i.push_back(99) + >>> i.push_back(98) + >>> i.__next__() + 98 + >>> i.__next__() + 99 + >>> i.__next__() + 1 + >>> i.__next__() + 2 + >>> i.push_back(100) + >>> i.__next__() + 100 + >>> i.__next__() + Traceback (most recent call last): + ... + StopIteration + """ + + def __init__(self, source_iter: Iterator): + self.source_iter = source_iter + self.pushed_back: List[Any] = [] + + def __iter__(self) -> Iterator: + return self + + def __next__(self) -> Any: + if len(self.pushed_back) > 0: + return self.pushed_back.pop() + return self.source_iter.__next__() + + def push_back(self, item: Any): + self.pushed_back.append(item) + + class SamplingIterator(Iterator): """An iterator that simply echoes what source_iter produces but also collects a random sample (of size sample_size) of the stream that can be queried at any time. + .. note:: + Until sample_size elements have been seen the sample will be + less than sample_size elements in length. + + .. note:: + If sample_size is > len(source_iter) then it will produce a + copy of source_iter. + >>> import collections >>> import random @@ -89,7 +153,7 @@ class SamplingIterator(Iterator): return self def __next__(self) -> Any: - item = self.source_iter.__next__() # or raise + item = self.source_iter.__next__() self.stream_length_so_far += 1 # Filling the resovoir