Skip to content

Instantly share code, notes, and snippets.

@mondwan
Created December 22, 2015 15:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mondwan/5f6ccaef986a11217242 to your computer and use it in GitHub Desktop.
Save mondwan/5f6ccaef986a11217242 to your computer and use it in GitHub Desktop.
How to do binary search in python
from bisect import bisect_left
# Source https://docs.python.org/2/library/bisect.html
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment