-
-
Save afonasev/d6800bbbf27afdbf236fa2a96f8cf0c1 to your computer and use it in GitHub Desktop.
SequenceKeyWrapper (bisect with key)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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