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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.