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
文件时,它工作正常。另外,当我尝试在在线python插入器中运行此文件时,它也可以正常工作
我认为空行是问题。
[将该代码粘贴到解释器中时,您的binary_search
函数实际上变成了这个:
def binary_search(item_list,item):
start = 0
end = len(item_list) - 1
found = False
因为Python解释器会在遇到第一个空行后完成函数定义。较短的binary_search
函数版本不会执行任何操作,也不会返回任何内容。
尝试在删除了空行的Python解释器中粘贴函数定义。
打印以及调用函数对我都有效。您可能要检查您的缩进,因为它们在您的第一篇文章中被弄乱了(在编辑之前):
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
也调用该函数确实会返回结果:
IN: binary_search([1,2,3,4,5,6],2)
OUT: True
但是,如果列表未排序:
IN: binary_search([1,4,5,2,5,7],2)
OUT: False
因此,如果应该在两种情况下都可以使用,那么您可能需要看一下。
好,您需要运行定义的函数。
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
您定义了该函数,但没有运行它。