Python中的二进制搜索实现

编程入门 行业动态 更新时间:2024-10-08 10:56:58
本文介绍了Python中的二进制搜索实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试使用二进制搜索实现解决方案.我有一个数字列表

I am trying to implement a solution using binary search. I have a list of numbers

list = [1, 2, 3, 4, 6] value to be searched = 2

我写了这样的东西

def searchBinary(list, sval): low = 0 high = len(list) while low < high: mid = low + math.floor((high - low) / 2) if list[mid] == sval: print("found : ", sval) elif l2s[mid] > sval: high = mid - 1 else: low = mid + 1

但是当我尝试实现这一点时,出现了类似错误:索引超出范围.请帮助确定问题.

but when I am trying to implement this, I am getting an error like: index out of range. Please help in identifying the issue.

推荐答案

一些事情.

  • 您的命名不一致.另外,请勿将list用作变量名,否则会掩盖全局内置变量.

  • Your naming is inconsistent. Also, do not use list as a variable name, you're shadowing the global builtin.

    停止条件为while low <= high.这个很重要.

    The stopping condition is while low <= high. This is important.

    找到值时不会中断.这将导致无限递归.

    You do not break when you find a value. This will result in infinite recursion.

    def searchBinary(l2s, sval): # do not use 'list' as a variable low = 0 high = len(l2s) while low <= high: # this is the main issue. As long as low is not greater than high, the while loop must run mid = (high + low) // 2 if l2s[mid] == sval: print("found : ", sval) return elif l2s[mid] > sval: high = mid - 1 else: low = mid + 1

    现在,

    list_ = [1, 2, 3, 4, 6] searchBinary(list_, 2)

    输出:

    found : 2
  • 更多推荐

    Python中的二进制搜索实现

    本文发布于:2023-11-29 02:25:46,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1644927.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:Python

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!