NeighborList: Don't snap in values if they match exactly

This commit is contained in:
Florian Bruhin 2014-05-15 15:38:53 +02:00
parent f97c87628b
commit 8b13658eaf
2 changed files with 12 additions and 11 deletions

View File

@ -277,18 +277,14 @@ class SnapInTests(TestCase):
self.assertEqual(self.nl.idx, 2) self.assertEqual(self.nl.idx, 2)
def test_equal_bigger(self): def test_equal_bigger(self):
self.nl.fuzzyval = 9 self.nl.fuzzyval = 20
self.assertEqual(self.nl.nextitem(), 9) self.assertEqual(self.nl.nextitem(), 9)
self.assertEqual(self.nl.idx, 1) self.assertEqual(self.nl.idx, 1)
self.assertEqual(self.nl.nextitem(), 1)
self.assertEqual(self.nl.idx, 2)
def test_equal_smaller(self): def test_equal_smaller(self):
self.nl.fuzzyval = 9 self.nl.fuzzyval = 5
self.assertEqual(self.nl.previtem(), 9) self.assertEqual(self.nl.previtem(), 1)
self.assertEqual(self.nl.idx, 1) self.assertEqual(self.nl.idx, 2)
self.assertEqual(self.nl.previtem(), 20)
self.assertEqual(self.nl.idx, 0)
if __name__ == '__main__': if __name__ == '__main__':

View File

@ -110,12 +110,17 @@ class NeighborList(collections.abc.Sequence):
Args: Args:
offset: negative to get the next smaller item, positive for the offset: negative to get the next smaller item, positive for the
next bigger one. next bigger one.
Return:
True if the value snapped in (changed),
False when the value already was in the list.
""" """
op = operator.le if offset < 0 else operator.ge op = operator.le if offset < 0 else operator.ge
items = [(idx, e) for (idx, e) in enumerate(self._items) items = [(idx, e) for (idx, e) in enumerate(self._items)
if op(e, self.fuzzyval)] if op(e, self.fuzzyval)]
close_item = min(items, key=lambda tpl: abs(self.fuzzyval - tpl[1])) close_item = min(items, key=lambda tpl: abs(self.fuzzyval - tpl[1]))
self.idx = close_item[0] self.idx = close_item[0]
return self.fuzzyval not in self._items
@property @property
def items(self): def items(self):
@ -143,10 +148,10 @@ class NeighborList(collections.abc.Sequence):
# Value has been set to something not in the list, so we snap in to # Value has been set to something not in the list, so we snap in to
# the closest value in the right direction and count this as one # the closest value in the right direction and count this as one
# step towards offset. # step towards offset.
self._snap_in(offset) snapped = self._snap_in(offset)
if offset > 0: if snapped and offset > 0:
offset -= 1 offset -= 1
else: elif snapped:
offset += 1 offset += 1
self.fuzzyval = None self.fuzzyval = None
try: try: