简体   繁体   English

我的 for 循环随机卡住并且没有完成它的范围

[英]My for loop randomly gets stuck and doesnt complete its range

My for loop keeps stopping in main.我的 for 循环一直在 main 中停止。 It is supposed to call the def binarySearch 10000 times and add up the total number of guesses from each try.它应该调用 def binarySearch 10000 次并将每次尝试的猜测总数相加。 I notice when I lower the range down to 100, the for loop works MOST of the time.我注意到当我将范围降低到 100 时,for 循环大部分时间都有效。 It still sometimes just freezes and never prints anything.它有时仍然只是冻结并且从不打印任何东西。

import random

def binarySearch(left, right, x):

    counter = 0 #guesses per try

    while left <= right:
        counter+=1
        
        mid = (right + left) // 2
        
        if x == mid:
            return counter

        elif x > mid:
            left = mid

        elif x < mid:
            right = mid


def main():  

    guesses = 0 # total number of guesses

    ###Problem here###
    for x in range(10001):
        
        lef = 0     #min
        rig = 1000  #max
        num = random.randint(lef, rig) #random number
        guesses += binarySearch(lef, rig, num) #calls binarySearch and sums the total guesses

        
    print("Total guesses from 10000 tries: ", guesses)


main()

EDIT: I narrowed down the problem to:编辑:我将问题缩小为:

elif x < mid: left = mid elif x < 中:左 = 中

I tested it quite a few times and came to the conclusion that the while loop ends up getting stuck repeating that else if statement.我测试了好几次,得出的结论是 while 循环最终会卡住重复 else if 语句。 I do not know why this is happening though.我不知道为什么会这样。

The reason it is getting stuck is because there is an error in the boundary condition.它卡住的原因是因为边界条件有错误。 If the number is not equal to mid and the left and right should be equal to mid + 1 and mid - 1 respectively.如果数字不等于mid,那么left和right应该分别等于mid + 1mid - 1 No need to consider mid again.没必要再考虑mid了。 Since you are considering mid again and again, your condition is never coming out of this cycle and hence the infinite loop.由于您一次又一次地考虑 mid ,因此您的条件永远不会出现在这个循环中,因此永远不会出现无限循环。

elif x > mid:
    left = mid + 1

elif x < mid:
    right = mid - 1

These should be your new values for left and right.这些应该是您的左右新值。 No need to consider mid again because it is not equal to the target value, if it were, the top most if the condition would have been true.不需要再次考虑 mid 因为它不等于目标值,如果是的话,如果条件为真,则最顶层。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM