[英]How do I fix this error in my Binary Search Python Code
I am learning about Binary Search in python and I decided that I want to implement it in actual code instead of just theory, so I found some examples and wrote some code.我正在学习 python 中的二进制搜索,我决定要在实际代码中实现它,而不仅仅是理论,所以我找到了一些例子并编写了一些代码。 This is the code that I have written:
这是我写的代码:
listData = [45, 125, 133, 192, 212, 256, 281, 283, 311, 358, 418, 424, 451, 483, 503, 567, 597,
602, 628, 651, 652, 677, 643, 778, 800, 805, 823, 842, 930, 945]
def binarySearch(listData, value):
low = 0
high = len(listData)
while (low <= high):
mid = (low+high)/2
if (listData[mid] == value):
return mid
elif (listData[mid] < value):
low = mid + 1
else:
high = mid - 1
return -1
print(binarySearch(listData, 45))
When I run this I get an error, this is the error:当我运行这个我得到一个错误,这是错误:
Traceback (most recent call last):
File "C:\Users\Bobby Singh\Desktop\binaryalgosearch.py", line 16, in <module>
print(binarySearch(listData, 45))
File "C:\Users\Bobby Singh\Desktop\binaryalgosearch.py", line 8, in binarySearch
if (listData[mid] == value):
TypeError: list indices must be integers or slices, not float
Can anyone help me with this?谁能帮我这个? Sorry for the bad formatting.
抱歉格式不正确。
Your high
index should be high = len(listData) - 1
since the highest index for a list is lenght - 1
您的
high
索引应该是high = len(listData) - 1
因为列表的最高索引是lenght - 1
Also, you need to round the mid
since it can give 0.5
for cases that are odd.此外,您需要舍入
mid
因为它可以为奇数的情况提供0.5
。 so do mid = round((low+high)/2)
所以做
mid = round((low+high)/2)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.