python - 二进制搜索 python 3.5

标签 python runtime-error binary-search python-3.5

我正在尝试在 python 3.5 中编写二进制搜索,但它不会工作我不确定为什么。

def binarySearch(alist, value):

    first = 0
    last = len(alist)-1
    midpoint = (last//2)
    while binarySearch:
        if value == alist[midpoint]:
            return True and print ("found")
        else:
            if value < midpoint:
                last = midpoint-1
            else:
                if value > midpoint:
                    first = midpoint+1    
binarySearch([1,2,3,4,5,6,7,8],3)

如果我将值设置为 4,它会显示已找到,如果我设置任何其他值,则什么也不会发生,并且它一直在运行,什么也不做。

感谢您的帮助。

最佳答案

User1915011 抢先回答了我。根据他的回答和@wim 的评论,我对您的 binarySearch 进行了以下更改。方法。

  1. 将循环更改为使用 found变量
  2. midpoint 添加了额外的分配循环内
  3. 通过添加 first<=last 确保循环终止
  4. while之后返回发现循环以指示成功或失败。

    def binarySearch(alist, value):
    
        first = 0
        last = len(alist)-1
        found = False
        while first<=last and not found:
            midpoint = (first + last)//2
            if value == alist[midpoint]:        
                found =  True 
            else:
                if value < alist[midpoint]:
                    last = midpoint-1
                else:
                    if value > midpoint:
                        first = midpoint+1  
        return found
    
    if binarySearch([1,2,3,4,5,6,7,8],3):
        print "found"
    

关于python - 二进制搜索 python 3.5,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34420006/

相关文章:

vba - 应用程序定义或对象定义错误 1004

javascript - 碰撞检测在吃 bean 人游戏中不起作用

c++ - 简单 C++ 代码上的运行时错误信号 11

python - 将python代码转换为c代码难吗?

java - 在未排序的字符串数组中搜索

python - 为什么 python 在解释之前将源代码编译为字节码?

python - 从两个 Numpy 数组高效生成柯西矩阵

python - 如何在 Python 中逐行打印字典?

java - 如何通过二进制搜索搜索 ArrayList 中的任何值

Python输入函数,打印