簡體   English   中英

我正在嘗試在終端中運行二進制搜索算法(Python),但沒有打印到終端

[英]I am trying to run a binary search algorithim (Python) in terminal but nothing prints to the terminal

def binary_search(item_list,item):

    start = 0
    end = len(item_list) - 1
    found = False

    while (start <= end and not found):
        mid = (start + end) // 2
        if item_list[mid] == item:
            print(item)
            found = True
        else:
            if item_list[mid] < item:
                start = mid + 1
            else:
                end = mid -1
    return found






my_big_array = list(range(10000))
my_big_number = 256

print(my_big_array)

print(binary_search(my_big_array,my_big_number))

我嘗試在終端中運行它,但什么也沒發生,但是當我創建一個打印 hello world 的hello_world.py文件時,它工作正常。 此外,當我嘗試在在線 python 解釋器中運行此文件時,它工作得很好

我認為你的問題是一個縮進問題,你的回報是在 while 循環中。 此外,您的第一個 else 也縮進很嚴重。 你的 else 必須和你的 if 有相同的縮進。 我測試了您的代碼,當我更正縮進時它可以工作。

我希望那將能夠幫助你

我認為空行是問題所在。

當您將該代碼粘貼到解釋器中時,您的binary_search function 有效地變為:

def binary_search(item_list,item):
    start = 0
    end = len(item_list) - 1
    found = False

因為 Python 解釋器在它遇到的第一個空行之后完成了 function 定義。 binary_search function 的較短版本並沒有做太多,也沒有返回任何東西。

嘗試將 function 定義粘貼到 Python 解釋器中,並刪除空行。

打印和調用 function 對我有用。 您可能需要檢查您的縮進,因為這些在您的第一篇文章中(在編輯之前)被搞砸了:

OUT: runfile(...)
OUT: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61...]
OUT: 256
OUT: True

也調用 function 確實返回結果:

IN: binary_search([1,2,3,4,5,6],2)
OUT: True

但是,如果列表未排序:

IN: binary_search([1,4,5,2,5,7],2)
OUT: False

所以你可能想看看它是否應該在這兩種情況下都有效。

那么你需要運行定義的 function。

def binary_search(item_list,item):

    start = 0
    end = len(item_list) - 1
    found = False

    while (start <= end and not found):
        mid = (start + end) // 2
        if item_list[mid] == item:
                print(item)
                found = True
            else:
                if item_list[mid] < item:
                    start = mid + 1
                else:
                    end = mid -1
        return found






    my_big_array = list(range(10000))
    my_big_number = 256

    print(my_big_array)

    print(binary_search(my_big_array,my_big_number)) 


binary_search(i,j) #where i and j is the parameters passed into the function

您定義了 function,但您沒有運行它。

暫無
暫無

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

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