Time for an 2014 update…
This commit is contained in:
parent
372c577f83
commit
09687c4926
2520 changed files with 34227 additions and 7318 deletions
6
Task/Binary-search/Python/binary-search-4.py
Normal file
6
Task/Binary-search/Python/binary-search-4.py
Normal 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
|
||||
12
Task/Binary-search/Python/binary-search-5.py
Normal file
12
Task/Binary-search/Python/binary-search-5.py
Normal 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
|
||||
Loading…
Add table
Add a link
Reference in a new issue