请查看以下代码:
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奇怪行为中的二进制搜索
发布评论