def bi_search(nums, target):
low = 0
high = len(nums)-1
while low <= high:
mid = (low+high)//2
if target == nums[mid]:
return mid
elif target < nums[mid]:
high = mid-1
else:
low = mid+1
return None
def test():
nums0 = [1,2,4,6,7,8,9,11,13,15,16,17,20,21,22,26,27,30]
assert bi_search(nums0, target=1) == 0
assert bi_search(nums0, target=6) == 3
assert bi_search(nums0, target=14)== None
print('All testcases pass!')
if __name__ == '__main__':
test()
结果:
$ python3 t.py
All testcases pass!
def mySqrt(x, eps=0.01):
if x in [0, 1]:
return x
low = 0
high = x
guess = (low+high)/2
while abs(guess ** 2 - x) > eps:
guess = (low+high)/2
if guess ** 2 < x:
low = guess
else:
high = guess
return guess
以上代码还可以增加对 x 的限制(非负数)、在 while 循环中统计迭代次数并作出限制、对精度做出限制。
def test():
for x in [0,1,2,3,4,9,10,15,16,100]:
print('%s的平方根:%s' %(x, mySqrt(x)))
if __name__ == '__main__':
test()
结果:
$ python3 t.py
0的平方根:0
1的平方根:1
2的平方根:1.4140625
3的平方根:1.734375
4的平方根:2.0
9的平方根:3.00146484375
10的平方根:3.16162109375
15的平方根:3.8726806640625
16的平方根:4.0
100的平方根:9.999847412109375
def sqrt_newton(x, eps=0.01):
if x == 0:
return 0
res = x
while abs(res-x/res)>eps:
res = (res+x/res)/2.0
return res
def test():
for x in [0, 1, 2, 3, 4, 9, 10, 16, 100]:
print(x, ' --> ', sqrt_newton(x))
if __name__ == '__main__':
test()
结果:
$ python3 sqrt_newton.py
0 --> 0
1 --> 1
2 --> 1.4166666666666665
3 --> 1.7321428571428572
4 --> 2.000609756097561
9 --> 3.00009155413138
10 --> 3.16245562280389
16 --> 4.002257524798522
100 --> 10.000052895642693