顺序查找,时间复杂度O(N);
二分查找,时间复杂度O(logN),但是二分查找要求顺序表。
函数:enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中.
enumerate(sequence,[start=0])
seasons = [‘Spring‘, ‘Summer‘, ‘Fall‘, ‘Winter‘]
list(enumerate(seasons))
[(0, ‘Spring‘), (1, ‘Summer‘), (2, ‘Fall‘), (3, ‘Winter‘)]
def linear_serach(list, value): for ind, v in enumerate(list): if v == value: return ind else: return None def bineary_search(list, val): b = 0 # begin e = len(list) - 1 # end while b <= e: m = (b + e) // 2 # end if list[m] == val: return m elif list[m] < val: #目标值在mid的右侧 b = m + 1 else: e = m - 1 else: #找不到值 return None list_test = [1, 2, 3, 4, 5, 6, 7, 8, 9] print(linear_serach(list_test, 7)) print(bineary_search(list_test, 10))
原文:https://www.cnblogs.com/ua-21/p/15028432.html