Time for an 2014 update…

This commit is contained in:
Ingy döt Net 2014-01-17 05:32:22 +00:00
parent 372c577f83
commit 09687c4926
2520 changed files with 34227 additions and 7318 deletions

View file

@ -0,0 +1,6 @@
from bisect import bisect_left
def binary_search(a, x, lo=0, hi=None): # can't use a to specify default for hi
hi = hi if hi is not None else len(a) # hi defaults to len(a)
pos = bisect_left(a,x,lo,hi) # find insertion position
return (pos if pos != hi and a[pos] == x else -1) # don't walk off the end

View file

@ -0,0 +1,12 @@
def binary_search(l, value):
low = 0
high = len(l)-1
while low + 1 < high:
mid = (low+high)//2
if l[mid] > value:
high = mid
elif l[mid] < value:
low = mid
else:
return mid
return high if abs(l[high] - value) < abs(l[low] - value) else low