我正在尝试 运行 终端中的二进制搜索算法 (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 拦截器中尝试 运行 这个文件时,它工作得很好

我认为空行是问题所在。

当您将该代码粘贴到解释器中时,您的 binary_search 函数实际上变成了:

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

因为Python解释器在遇到第一个空行之后就完成了函数定义。 binary_search 函数的较短版本没有做太多,也没有 return 任何东西。

尝试将您的函数定义粘贴到 Python 解释器中并删除空行。

打印和调用函数对我来说都很有效。您可能需要检查您的缩进,因为这些在您的第一个 post(编辑之前)中被弄乱了:

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

同时调用该函数 return 结果:

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

但是,如果列表未排序:

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

所以您可能想看看它是否适用于这两种情况。

我认为你的问题是缩进问题,你的return在while循环中。此外,您的第一个 else 缩进也很严重。您的 else 必须与您的 if 具有相同的缩进。我测试了您的代码,当我更正缩进时它可以正常工作。

希望对你有所帮助