Last active
August 9, 2022 20:44
-
-
Save ericremoreynolds/2d80300dabc70eebc790 to your computer and use it in GitHub Desktop.
Key-like functionality recipe for Python's bisect functions
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 KeyifyList(object): | |
def __init__(self, inner, key): | |
self.inner = inner | |
self.key = key | |
def __len__(self): | |
return len(self.inner) | |
def __getitem__(self, k): | |
return self.key(self.inner[k]) | |
if __name__ == '__main__': | |
import bisect | |
L = [(0, 0), (1, 5), (2, 10), (3, 15), (4, 20)] | |
assert bisect.bisect_left(KeyifyList(L, lambda x: x[0]), 3) == 3 | |
assert bisect.bisect_left(KeyifyList(L, lambda x: x[1]), 3) == 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Wonderful, works for any
Sequence
.