Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
420 views
in Technique[技术] by (71.8m points)

python - My for loop randomly gets stuck and doesnt complete its range

My for loop keeps stopping in main. It is supposed to call the def binarySearch 10000 times and add up the total number of guesses from each try. I notice when I lower the range down to 100, the for loop works MOST of the time. 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

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. I do not know why this is happening though.

question from:https://stackoverflow.com/questions/65949114/my-for-loop-randomly-gets-stuck-and-doesnt-complete-its-range

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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. No need to consider mid again. Since you are considering mid again and again, your condition is never coming out of this cycle and hence the infinite loop.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...