简体   繁体   English

在while循环外部还是内部变量?

[英]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 ?为什么当变量midmid_val在 while 循环之外定义时,我的 function 不起作用,就像lowhigh一样?

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.如果lowhigh的值发生变化, mid不会自动更新。 So you need this assignment in the while loop to update mid .因此,您需要在 while 循环中进行此分配来更新mid

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在while循环内进行的变量更改未反映在Python 3的循环外 - Change in variable made inside of a while loop is not reflected outside of the loop in Python 3 在for循环内和在for循环外声明变量的区别 - Difference of declaring variable inside for loop and outside for loop Python - for 循环内的变量在循环外消失 - Python - variable inside for loop disappears outside of loop 在Python的while循环外自动更改变量的值 - Autochange values of a variable outside a while loop in Python 访问while循环之外的变量,Python - Accessing a variable outside of a while loop, Python 在 while 循环之外访问变量值 - Accessing a variable value outside of a while loop 在while循环之外更改while循环的条件变量的状态 - Change the state of the condition variable for a while loop outside the while loop 将 dataframe 分配给 for 循环外部的变量,或在 Python 的 for 循环内部直接使用它 - Assign dataframe to variable outside for loop or use it directly inside for loop in Python 我应该在while循环内还是外部提交到数据库? - Should I commit to my database inside the while loop or outside? Gobal变量,但在while循环内,而不在函数中 - Gobal Variable but inside the while loop and not in a function
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM