Created
August 26, 2013 05:11
-
-
Save jaredks/6338274 to your computer and use it in GitHub Desktop.
Set with constant time operations. Also maintains order and will remove older elements to make room for newer ones, allowing up to maxlen elements.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from collections import MutableSet as _MutableSet, OrderedDict as _OrderedDict | |
from itertools import chain as _chain | |
class SetQueue(_MutableSet): | |
def __init__(self, iterable=(), maxlen=None): | |
self._queue = _OrderedDict() | |
self._maxlen = maxlen | |
self.update(iterable) | |
def __iter__(self): | |
return iter(self._queue) | |
def __len__(self): | |
return len(self._queue) | |
def __contains__(self, value): | |
return value in self._queue | |
def __repr__(self): | |
return '{}([{}]{})'.format(self.__class__.__name__, ', '.join(map(str, iter(self))), | |
', maxlen=' + str(self.maxlen) if self.maxlen is not None else '') | |
@property | |
def maxlen(self): | |
return self._maxlen | |
def add(self, value): | |
if value not in self: | |
if self.maxlen is not None and len(self) == self.maxlen: | |
self._queue.popitem(last=False) | |
self._queue[value] = 1 | |
def discard(self, value): | |
self._queue.pop(value, None) | |
def pop(self, first=True): | |
return self._queue.popitem(not first)[0] | |
def update(self, *iterables): | |
for ele in _chain.from_iterable(iterables): | |
self.add(ele) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment