Skip to content

Instantly share code, notes, and snippets.

@ProgVal ProgVal/history.py
Created Jul 25, 2013

Embed
What would you like to do?
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
You can’t perform that action at this time.