首页 > 解决方案 > 我正在尝试在终端中运行二进制搜索算法(Python),但没有打印到终端

问题描述

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.py打印 hello world 的文件时,它工作正常。此外,当我尝试在在线 python 解释器中运行此文件时,它工作得很好

标签: pythonbinary-search

解决方案


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

我希望那将能够帮助你


推荐阅读