#二分法原理 ''' 从中间位置开始,通过判断是>或者<后,再对其取中间位置,依次类推直到区间长度等于1 ''' ''' 二分法将遍历的次数缩小到了原来的log2X倍 但二分法的前提条件是所有的数据排列是有序的 ''' #code
def binary_search(a,item):
#设定初始条件
low = 0
high = len(a)-1
while low<=high:
mid = (low + high) // 2
if a[mid] == item:
return True
elif a[mid]>item:
high = mid-1
else:
low = mid+1
return False
my_list = [1,3,5,7,9]
print(binary_search(my_list,9))
print(binary_search(my_list,5))
#为什么只改变列表元素的长度就会导致结果变换 ''' 因为我的原始代码中guess的固定在初始化中没有随着更新, 所以guess固定与list中间的位置



