Skip to content

Instantly share code, notes, and snippets.

@progval
Created July 25, 2013 19:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save progval/6082995 to your computer and use it in GitHub Desktop.
Save progval/6082995 to your computer and use it in GitHub Desktop.
Limited-length sorted list.
import bisect
import operator
import unittest
class history:
"""Limited-length sorted list."""
def __init__(self, maxlen):
self._maxlen = maxlen
self._list = []
def __repr__(self):
return 'upmonitor.database.history(%r)' % self._heap
def __len__(self):
return len(self._list)
# We do not implement __(get|del)item__ because it would not make sense
def __setitem__(self, timestamp, value):
self._list.insert(bisect.bisect_left(self._list, (timestamp, 0)),
(timestamp, value))
while len(self._list) > self._maxlen:
self._list.pop(0)
def __iter__(self):
return map(operator.itemgetter(1), self._list)
def items(self):
return self.__iter__()
def reverseitems(self):
return map(operator.itemgetter(1), reversed(self._list))
class TestHistory(unittest.TestCase):
def testRing(self):
history = history(maxlen=5)
for x in range(1, 10):
history[x*10 + 50] = str(x)
self.assertEqual(len(history), min(5, x), history)
self.assertEqual(len(list(history)), min(5, x), list(history))
def testOrder(self):
list_ = [(5, 'baz'), (3, 'bar'), (9, 'qux'), (1, 'foo'), (10, 'quux')]
history = history()
for (key, value) in list_:
history[key] = value
self.assertEqual(list(history), 'foo bar baz qux quux'.split(' '))
self.assertEqual(list(history.items()),
'foo bar baz qux quux'.split(' '))
self.assertEqual(list(history.reverseitems()),
'quux qux baz bar foo'.split(' '))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment