python奇怪行为中的二进制搜索

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

请查看以下代码:

def chop(array, search): lo = 0 high = len(array) - 1 while lo <= high: mid = (high + lo) /2 if array[mid] == search: return 'true' elif search > array[mid]: low = mid + 1 else: high = mid - 1 return 'false' if __name__ == '__main__': a = [1,2,3,4,5,6,7,8,9,10] print chop(a, 3)

我写了这个小脚本,该脚本应该在数组中搜索数字-常规二进制搜索.因此,我运行了脚本,例如,当我放入chop(a, 1)时,我就得到了真,而当我放入chop(a, 2)时,我就得到了,但是当我放入chop(a, 3)时,我没有得到任何答案,只是在其中插入了空行Python Shell.

I wrote this little script which is supposed to search for number in array - regular binary search. So I run the script, and for example when I put in chop(a, 1) I get true, when I put in chop(a, 2) I get true, but when I put chop(a, 3) I don't get an answer, just empty line in the Python Shell.

有人对发生的事情有想法吗?

Does anyone have an idea on what is going on?

推荐答案

我猜这是您的错误:

low = mid + 1

您的while循环使用变量lo,并且您正在while循环中定义一个名为low的新变量.本质上,您永远不会更新lo变量.

Your while loop uses the variable lo, and you're defining a new variable called low within your while loop. In essence, you're never updating your lo variable.

将该行更改为:

lo = mid + 1

您的算法应该可以使用.

and your algorithm should work.

更多推荐

python奇怪行为中的二进制搜索

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

发布评论

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

>www.elefans.com

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