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/

相关文章:

python - 如何在python中编写代理池服务器(请求来时,选择代理获取url内容)?

python - 访问 PyObject 的底层结构

java - 使用超出范围的索引拆分字符串

python - 如何检查整数小数点后的值是否为零

Python 编码和 json 转储

r - R 4.02 中大矩阵的 SVD 总线错误

c++ - 运行时错误 : map/set iterators incompatible

c - 为什么这个二分搜索会给我一个无限循环?

c - SPOJ - 好斗的奶牛, "largest minimum distance"术语的含义是什么?

arrays - 在 O(lgn) 中搜索部分排序的数组