[英]Variable outside or inside while loop?
Why doesn't my function work when the variables mid
and mid_val
are defined outside the while loop, just like low
and high
?为什么当变量
mid
和mid_val
在 while 循环之外定义时,我的 function 不起作用,就像low
和high
一样?
def binary_search(arr, x):
low = 0
high = len(arr) - 1
while low <= high:
mid = (low + high) // 2
mid_val = arr[mid]
if x == mid_val:
return mid
elif x > mid_val:
low = mid + 1
else:
high = mid - 1
return "Out of range"
array = [2,4,5,6]
x = 6
print(binary_search(array, x))
When you set the value of a variable with mid = (low + high) // 2
, the value is calculated using the current values of other variables.当您使用
mid = (low + high) // 2
设置变量的值时,将使用其他变量的当前值计算该值。 This is a one-and-done operation.这是一个一次性的操作。
mid
will not automatically update if the value of low
or high
changes.如果
low
或high
的值发生变化, mid
不会自动更新。 So you need this assignment in the while loop to update mid
.因此,您需要在 while 循环中进行此分配来更新
mid
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.