繁体   English   中英

如何在我的二进制搜索 Python 代码中修复此错误

[英]How do I fix this error in my Binary Search Python Code

我正在学习 python 中的二进制搜索,我决定要在实际代码中实现它,而不仅仅是理论,所以我找到了一些例子并编写了一些代码。 这是我写的代码:

    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))

当我运行这个我得到一个错误,这是错误:

    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

谁能帮我这个? 抱歉格式不正确。

您的high索引应该是high = len(listData) - 1因为列表的最高索引是lenght - 1

此外,您需要舍入mid因为它可以为奇数的情况提供0.5 所以做mid = round((low+high)/2)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM