Created
January 9, 2019 17:23
-
-
Save daryl314/87d82e2ec61d497031b02d1991c59d19 to your computer and use it in GitHub Desktop.
Helpers to find entries in a sorted list (using python bisect module)
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
from bisect import * | |
##### HELPER FUNCTIONS FROM PYTHON DOCUMENTATION ##### | |
def index(a, x): | |
'Locate the leftmost value exactly equal to x' | |
i = bisect_left(a, x) | |
if i != len(a) and a[i] == x: | |
return i | |
raise ValueError | |
def find_lt(a, x): | |
'Find rightmost value less than x' | |
i = bisect_left(a, x) | |
if i: | |
return a[i-1] | |
raise ValueError | |
def find_le(a, x): | |
'Find rightmost value less than or equal to x' | |
i = bisect_right(a, x) | |
if i: | |
return a[i-1] | |
raise ValueError | |
def find_gt(a, x): | |
'Find leftmost value greater than x' | |
i = bisect_right(a, x) | |
if i != len(a): | |
return a[i] | |
raise ValueError | |
def find_ge(a, x): | |
'Find leftmost item greater than or equal to x' | |
i = bisect_left(a, x) | |
if i != len(a): | |
return a[i] | |
raise ValueError | |
##### HELPERS TO RETURN INDICES ##### | |
def index_left(a, x): | |
'Locate the leftmost value exactly equal to x' | |
return index(a, x) | |
def index_right(a, x): | |
'Locate the rightmost value exactly equal to x' | |
i = bisect_right(a, x) | |
if i>0 and a[i-1] == x: | |
return i-1 | |
raise ValueError | |
def find_lt_index(a, x): | |
'Find index of rightmost value less than x' | |
i = bisect_left(a, x) | |
if i: | |
return i-1 | |
raise ValueError | |
def find_le_index(a, x): | |
'Find index of rightmost value less than or equal to x' | |
i = bisect_right(a, x) | |
if i: | |
return i-1 | |
raise ValueError | |
def find_gt_index(a, x): | |
'Find index of leftmost value greater than x' | |
i = bisect_right(a, x) | |
if i != len(a): | |
return i | |
raise ValueError | |
def find_ge_index(a, x): | |
'Find index of leftmost item greater than or equal to x' | |
i = bisect_left(a, x) | |
if i != len(a): | |
return i | |
raise ValueError |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment