Skip to content

Instantly share code, notes, and snippets.

@ProgVal ProgVal/
Created Jul 25, 2013

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:
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(' '))
'foo bar baz qux quux'.split(' '))
'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.