Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/reporting-services/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
未找到时退出循环-Python中的二进制搜索_Python_Search - Fatal编程技术网

未找到时退出循环-Python中的二进制搜索

未找到时退出循环-Python中的二进制搜索,python,search,Python,Search,我正在做一个二进制搜索程序来搜索列表中的一个数字。以下是目前的节目。如果在列表中找到某个数字,我要求程序查找该数字的索引,否则,它应返回“not found” 但是如果没有找到数字,下面的代码不会退出循环。我怎样才能做到这一点 def binary_search(n): l = [1,6,7,10,19,24,42,81] low = 0 high = len(s)-1 index = (high + low)/2 while s[index] != n:

我正在做一个二进制搜索程序来搜索列表中的一个数字。以下是目前的节目。如果在列表中找到某个数字,我要求程序查找该数字的索引,否则,它应返回“not found”

但是如果没有找到数字,下面的代码不会退出循环。我怎样才能做到这一点

def binary_search(n):
    l = [1,6,7,10,19,24,42,81]
    low = 0
    high = len(s)-1
    index = (high + low)/2
    while s[index] != n:
        if s[index] < n:
            low = index + 1
        else:
            high = index
        index = (high + low)/2

binary_search(43)

在函数调用之前,但正如我所说,如果无法找到数字,循环不会退出。

这是因为
while
循环的条件。循环将继续,直到在列表中找到元素为止。因此,当元素不在列表中时,循环不会中断。您可以通过在每次迭代中打印
high
low
index
的值来调试代码


要确认元素不在列表中,可以检查其他条件。当
low>=high
为true时,表示搜索范围为空,因此元素不在列表中。

如果没有元素,则需要中断while循环。您可以添加如下条件:

while s[index] != n:
    if low>=high:
        return "Not Found"
    if  s[index] < n:
        low = index + 1 
    else:
        high = index
    index = (high + low)/2

您是否尝试过在其内部使用if语句,然后在符合这些条件时使用
break
?是的,我尝试添加break,但即使找不到它,结果仍然是5。我在最小最大数之前给出了位置。谢谢!你的编辑很棒,但既然没有条件,我怎么能现在打印不到呢?那太容易了。一种方法是不打印,而是使用
返回索引
而不是
打印索引
从循环返回,并从
二进制搜索
函数返回
“未找到”
@你为什么在接受了答案后又不接受它?
while s[index] != n:
    if low>=high:
        return "Not Found"
    if  s[index] < n:
        low = index + 1 
    else:
        high = index
    index = (high + low)/2
while low<high:
    if l[index] == n:
        print index
    if  l[index] < n:
        low = index + 1 
    else:
        high = index
    index = (high + low)/2