簡體   English   中英

我的代碼有效,但我認為我使用的方法不正確

[英]My code works but I don't think I'm using the right method

摘要: Function 在數組中搜索一個數字,如果找到它將返回 found 等。代碼有效,它給了我正確的響應,但這是設置數組的正確方法,還是搜索列表? 我是編程新手,我相信數組更好(更快)不知道為什么?

array = [2, 3, 5, 7, 11, 13, 17, 19, 
23, 29, 31, 37, 41, 43, 
    47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]

targetValue = int(input())


def binarySearch(array, targetValue):
    min = 0
    max = len(array) - 1
    found = 'Number is not in array'

    while (min <= max):
        middle = (min + max)/2

        if array[middle] == targetValue:
            found = 'We found the number in the array!'
            return found

        else:
            if targetValue < array[middle]:
                max = middle - 1
            else: 
                min = middle + 1
    return found


index = binarySearch(array, targetValue)
print (index)
  • 代碼本身看起來不錯; 主要反饋是(在 Python 3 中) /運算符將給出浮點數(例如5 / 2給出 2.5)。 您可能需要//運算符,它給出整數(例如5 // 2給出 2)。

  • 如果您在實際項目中使用它(而不是作為練習),標准庫有一個bisect模塊,它正是這樣做的。

  • 至於為什么更快,想想它有多少次通過循環到go; 每次通過它都會消除一半的數組; 有 25 個元素,它只需要 go 最多約 5 次(log₂ 25)。 更重要的是,它將很好地擴展——將數組的大小增加一倍只會增加一個額外的循環,增加 10 倍只會增加 3-4 次循環,增加 1000 倍只會增加 10 次循環。

這是一個簡化版本:

array = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]
targetValue = int(input())

def binarySearch(array, targetValue):
    min = 0
    max = len(array) - 1
    while True:
        middle = (min + max)//2
        if array[middle] == targetValue:
            return 'We found the number in the array!'
        if targetValue < array[middle]:
            max = middle - 1
        else: 
            min = middle + 1

index = binarySearch(array, targetValue)
print (index)

這看起來大部分是正確的。 一個問題是這里:

middle = (min + max)/2
if array[middle] == targetValue:

中間可能不是 integer,它可能是除法后的浮點數。 所以你需要將它包裝在一個int調用中:
middle = int((min+max)/2.0)

我假設這是一個編碼練習,有很多“更簡單”的方法可以實現這一點,例如: if targetValue in array - 請注意您的變量array是 python list ,而不是array object。

看來您在 Python 中實現了您的二進制搜索算法,所以要回答您的問題,是的,您正確定義了一個數組。 在 python 中,“列表”實際上是一個動態數組。

然而 Python 確實有一個原生數組類型。 您可以查看此線程以了解有關主題Python 列表與數組 - 何時使用? .

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM