Skip to content

Instantly share code, notes, and snippets.

@luisenriquecorona
Created December 21, 2019 03:57
Show Gist options
  • Save luisenriquecorona/7efbb2e48044f4815081dadad87da9cd to your computer and use it in GitHub Desktop.
Save luisenriquecorona/7efbb2e48044f4815081dadad87da9cd to your computer and use it in GitHub Desktop.
bisect(haystack, needle) does a binary search for needle in haystack — which must be a sorted sequence — to locate the position where needle can be inserted while maintaining haystack in ascending order. In other words, all items appearing up to that position are less or equal to needle.
import bisect
import sys
HAYSTACK = [1, 4, 5, 6, 8, 12, 15, 20, 21, 23, 23, 26, 29, 30]
NEEDLES = [0, 1, 2, 5, 8, 10, 22, 23, 29, 30, 31]
ROW_FMT = '{0:2d} @ {1:2d} {2}{0:<2d}'
def demo(bisect_fn):
for needle in reversed(NEEDLES):
position = bisect_fn(HAYSTACK, needle)
offset = position * ' |'
print(ROW_FMT.format(needle, position, offset))
if __name__ == '__main__':
if sys.argv[-1] == 'left':
bisect_fn = bisect.bisect_left
else:
bisect_fn = bisect.bisect
print('DEMO:', bisect_fn.__name__)
print('haystack ->', ' '.join('%2d' % n for n in HAYSTACK))
demo(bisect_fn)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment