簡體   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