在看算法图解的过程了解到了不少算法的知识,但在中间也遇到了一个小问题。
下面咱们就看一下这个小问题时怎么解决的。
下面是书中的源码:python
def binary_search(list, item): low = 0 high = len(list) while low <= high: mid = (low + high) / 2 guess = list[mid] if guess == item: return mid if guess > item: high = mid - 1 else: low = mid - 1 return None
当咱们用下面的数据运行时:算法
list = [1, 2, 3, 4, 5] item = 3 position = binary_search(list, item) print(position)
会致使以下错误:测试
Traceback (most recent call last): File "binary_search.py", line 17, in <module> position = binary_search(list, item) File "binary_search.py", line 6, in binary_search guess = list[mid] TypeError: list indices must be integers or slices, not float
上面信息的意思是索引类型错误,索引必须为整型而不是float型。
这是由于python中除法即“/”会自动转换类型。将没法整除的数字转换成浮点型。
下面是我一开始想到的解决办法:code
def binary_search(list, item): low = 0 high = len(list) while low <= high: mid = int((low + high) / 2) # 将结果加一个类型转换便可 guess = list[mid] if guess == item: return mid if guess > item: high = mid - 1 else: low = mid - 1 return None
但当使用下面的数据进行测试时:索引
list = [1, 2, 3, 4, 5] item = 5 position = binary_search(list, item) print(position)
结果就是循环不会中止了。
为了找到问题出在哪里。咱们在循环体中加一个pirnt语句输出一下mid源码
def binary_search(list, item): low = 0 high = len(list) while low <= high: mid = int((low + high) / 2) # 将结果加一个类型转换便可 print(mid) guess = list[mid] if guess == item: return mid if guess > item: high = mid - 1 else: low = mid - 1 return None
仍是使用上面的数据运行一下。
能够在终端中看到一直在循环输出3。
出现这个问题缘由就处在int() 这个取整的操做他不是咱们理解的四舍五入,而是简单的截取整数部分。
看下面的例子。it
a = 5.4 b = 5.5 c = 5.6 print(int(a)) print(int(b)) print(int(c))
运行后输出为:io
5 5 5
为了解决这个问题咱们只须要给要取整的数加一个0.5便可。
上面的例子修改成:ast
a = 5.4 b = 5.5 c = 5.6 print(int(a + 0.5)) print(int(b + 0.5)) print(int(c + 0.5))
运行后输出为:module
5 6 6
因此上面的二分查找也就能够修改为:
def binary_search(list, item): low = 0 high = len(list) while low <= high: mid = int((low + high) / 2 + 0.5) # 为了实现四舍五入加上一个0.5 guess = list[mid] if guess == item: return mid if guess > item: high = mid - 1 else: low = mid - 1 return None
这样解决了二分查找中的这个小问题。