Skip to content

Instantly share code, notes, and snippets.

@DavidMertz
Created January 1, 2019 02:28
Show Gist options
  • Save DavidMertz/6394b4bce3b9fc6e6888c6c013d8ee2c to your computer and use it in GitHub Desktop.
Save DavidMertz/6394b4bce3b9fc6e6888c6c013d8ee2c to your computer and use it in GitHub Desktop.
MonotonicExpandingSequence
# A bit of cleverness to create a new sequence for infinite iterators
from collections.abc import Sequence
class MonotonicExpandingSequence(Sequence):
def __init__(self, iterator):
self.iterator = iterator
self._cache = []
def __getitem__(self, index):
while len(self._cache) <= index:
self._cache.append(next(self.iterator))
return self._cache[index]
def __len__(self):
return len(self._cache)
def __contains__(self, num):
i = 0
while True:
if self[i] == num:
return True
elif self[i] > num:
return False
else:
i += 1
# Usage, e.g.:
# primes = MonotonicExpandingSequence(get_all_primes())
# if 257 in primes: ...
# if 258 in primes: ...
# n = primes[100]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment