首页 > 代码库 > 使用python实现二分法

使用python实现二分法

def f1(src_list,find_n):
    if find_n > src_list[-1]:                                #判断find_n是否大于最大值,如果大于则直接返回
        = "%s is not finded" % (find_n)
        print(s)
        return False
    if find_n < src_list[0]:                                 #判断find_n是否小于最小值,如果小于则直接返回
        = "%s is not finded" % (find_n)
        print(s)
        return False
    else:                                                   #只有find_n在最大值和最小值之间,才进入函数
        mid = int(len(src_list)/2)
        if len(src_list) > 1:
            if src_list[mid] > find_n:
                print("%s in left" %(find_n))
                mid_list = src_list[0:mid]
                f1(mid_list,find_n)
            elif src_list[mid] < find_n:
                print("%s in right" %(find_n))
                mid_list = src_list[mid:]
                f1(mid_list,find_n)
            else:
                print("%s is finded" %(find_n))
                return True
        if len(src_list) == 1:
            if src_list[0== find_n:
                = "%s is finded" % (find_n)
                print(s)
                return True
            else:
                = "%s is not finded" % (find_n)
                print(s)
                return False
data = list(range(0,10,3))
f1(data,-1)


使用python实现二分法