Skip to content

Instantly share code, notes, and snippets.

@afonasev
Created March 14, 2018 09:47
Show Gist options
  • Save afonasev/d6800bbbf27afdbf236fa2a96f8cf0c1 to your computer and use it in GitHub Desktop.
Save afonasev/d6800bbbf27afdbf236fa2a96f8cf0c1 to your computer and use it in GitHub Desktop.
SequenceKeyWrapper (bisect with key)
class SequenceKeyWrapper(object):
"""
for bisect with key function
"""
def __init__(self, iterable, key):
self.iterable = iterable
self.key = key
def __getitem__(self, i):
return self.key(self.iterable[i])
def __len__(self):
return len(self.iterable)
def test_bisect_found_with_sequence_key_wrapper():
data = [('black', 0), ('blue', 1), ('red', 5), ('yellow', 8)]
wrapped_data = SequenceKeyWrapper(data, key=lambda c: c[1])
assert bisect.bisect_left(wrapped_data, 6) == 3
assert bisect.bisect_left(wrapped_data, 5) == 2
assert bisect.bisect_left(wrapped_data, 4) == 2
assert bisect.bisect_left(wrapped_data, -1) == 0
assert bisect.bisect_left(wrapped_data, 9) == 4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment