python之二分法查找
二分法查找主要的作用就是查找元素
规则. 掐头结尾取中间, 必须是有序列
# 二分法查找 (需要你明白和掌握) # lst = [1,3,5,7,12,36,68,79] # n = int(input("请输入一个数")) # # left = 0 # right = len(lst) - 1 # # while left <= right: # mid = (left + right)//2 # if n > lst[mid]: # left = mid + 1 # elif n < lst[mid]: # right = mid - 1 # else: # print("存在") # break # # else: # print("不存在")
# 递归二 (需要你明白和掌握) # def func(n, lst, left, right): # 递归找到什么是可以变的. 什么是不可以变的 # if left <= right: # mid = (left + right) // 2 # if n > lst[mid]: # left = mid + 1 # return func(n, lst, left, right) # elif n < lst[mid]: # right = mid - 1 # return func(n, lst, left, right) # 递归如果有返回值. 所有调用递归的地方必须写return # else: # print("找到了") # return mid # 难点 # else: # print("找不到") # return -1 # # n = int(input("请输入你要查找的数:")) # lst = [1,3,55,98,37,41,2,5,1,4] # ret = func(n, lst, 0, len(lst)-1) # 78 # print(ret)
# 最快的查找 lst = [1,3,55,98,37,41,2,5,1,4] new_lst = [] for i in range(99): new_lst.append(0) for i in lst: # 1,3,55,98 new_lst[i] = 1 print(new_lst) i = int(input('请输入你要找的数据')) if new_lst[i] == 0: # 1次 print("不存在") else: print("存在")