例如,
print(binary_search(7, [1, 5, 10])) # 2
print(binary_search(42, (-5, 1, 3, 5, 7, 10))) # 6
Run Code Online (Sandbox Code Playgroud)
我的代码:
def binary_search(x, seq):
if len(seq) == 0
low = 0
high = len(seq)
mid = (low+high)//2
if x == seq[mid]:
return mid
elif x < seq[mid]:
return binary_search(x,seq[:mid])
elif x > seq[mid]:
return mid + 1 + binary_search(x,seq[mid+1:]
Run Code Online (Sandbox Code Playgroud) python ×1