Skip to content

Instantly share code, notes, and snippets.

@arnobaer
Last active June 23, 2021 16:28
Show Gist options
  • Save arnobaer/6c1ffd25c5ff6c11de2af193cf23070b to your computer and use it in GitHub Desktop.
Save arnobaer/6c1ffd25c5ff6c11de2af193cf23070b to your computer and use it in GitHub Desktop.
bisect for ascending and descending series
def bisect_asc(arr):
if len(arr):
return arr[-1] < arr[0]
return True
def bisect_cmp(arr):
if bisect_asc(arr):
return lambda x, y: x > y
return lambda x, y: x < y
def bisect_right(arr, val):
l = -1
r = len(arr)
cmp = bisect_cmp(arr)
while r - l > 1:
e = (l + r) >> 1
if cmp(arr[e], val):
l = e
else:
r = e
return r
def bisect_left(arr, val):
l = -1
r = len(arr)
cmp = bisect_cmp(arr)
while r - l > 1:
e = (l + r) >> 1
if cmp(arr[e], val):
l = e
else:
r = e
return l
def slice(arr, minimum, maximum):
"""Slice ascending or descending range."""
a = max(0, bisect_left(arr, minimum))
b = max(0, bisect_right(arr, maximum))
if b - a > 1:
return arr[a:b+1]
if len(arr) <= 1:
return arr[a:b]
return []
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment