Python二分查找练习程序

Python二分查找练习程序

def find(sequence,data):
    """二分查找练习程序"""
    left = 0
    right = len(sequence)
    while left < right:
        mid = int((left + right)/2)            # 取序列中间索引号
        if data < sequence[mid]:right = mid    # 如果要找的数据比中间的小,则右边界为mid
        elif data > sequence[mid] :left = mid+1# 如果要找的数据比中间的大,则左边界为mid+1
        else: return mid                       # 否则刚好相等,则找到了
    return -1
        
nums = [3,7,16,23,33,99,133,155,331,776,889,1234]

# 下面是测试代码
assert find(nums,7)==1
assert not find(nums,33)==40

李兴球

李兴球的博客是Python创意编程原创博客