python - 我正在尝试在终端中运行二进制搜索算法(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 解释器中运行此文件时,它工作得很好
解决方案
我认为你的问题是一个缩进问题,你的回报是在 while 循环中。此外,您的第一个 else 也缩进很严重。你的 else 必须和你的 if 有相同的缩进。我测试了您的代码,当我更正缩进时它可以工作。
我希望那将能够帮助你
推荐阅读
- python - 创建线之间填充间隙的图表
- php - php - 名称在数组中的 Mysql
- javascript - 用于 Javascript 的 EMVCo TLV 字符串解析器库
- ios - 在 NSDIctionary 中设置值时 SIGSEGV 崩溃
- tensorflow - Tensorflow 对象检测 API - 错误对象检测
- jquery - 数据表在行中显示空数据
- laravel - laravel 跨多个表搜索
- javascript - 谷歌地图圈不呈现/显示
- java - 检索动态创建的布局 ID 并将其与列表条目匹配
- selenium - 在 Selenium 中,如何通过代码检索“FindsBy”属性的值?