[英]Guessing Game using Binary search
I am trying to make a guessing game using binary search我正在尝试使用二进制搜索进行猜谜游戏
here is my code:这是我的代码:
import random
def guess():
a = 0
b = 100
c = random.randint(1,100)
count = 1
user = int(input("Guess a number from 1 to 100: "))
comp = int(input(f"\nIs ur number {c}\nIf its high write 0 \nIf its low write 2\nIf it is then write 1: "))
while comp != 1:
count += 1
if comp == 0:
c = (a + c) // 2
elif comp == 2:
c = (c + b) // 2
comp = int(input(f"\nIs ur number {c} \nif its high press 0 \nif its low press 2\nif its ur number press 1: "))
print(f"\nYour number was {user} and it took {count} turn to find ur number.")
guess()
The problem i am facing is with the binary search我面临的问题是二进制搜索
for eg:例如:
assuiming our guess number is = 55
our random number genrated = 22
user will press 2 cause it low resulting a number = (22 + 100) // 2
= 61
since 61 in higher than 55
# here lies the problem in the 2nd loop
user will press 1 cause its high resulting a number = (0 + 61) // 2
= 30
It finds the middle number from 0 to 61 which i dont want它找到了我不想要的从 0 到 61 的中间数字
What i want is it to find the middle number for 22 something like this:我想要的是找到 22 的中间数字,如下所示:
(22 + 61) // 2 causing it to give us 41 (22 + 61) // 2 导致它给我们 41
then (41 + 61) // 2 causing it to print 51然后 (41 + 61) // 2 导致它打印 51
then (51 + 61) // 2 causing it to print 56然后 (51 + 61) // 2 导致它打印 56
then (56 + 51 ) // 2 causing it to print 53然后 (56 + 51 ) // 2 导致它打印 53
then (53 + 56 ) // 2 causing it to print 54然后 (53 + 56 ) // 2 导致它打印 54
then (54 + 56 ) // 2 causing it to print 55然后 (54 + 56 ) // 2 导致它打印 55
55 which is our guess number 55 这是我们的猜测数字
I made the following modifications to your function in order to narrow the interval of research as itprorh66 suggested.我对您的 function 进行了以下修改,以便按照itprorh66的建议缩小研究间隔。 The code is the following:
代码如下:
def guess():
a = 0
b = 100
c = random.randint(1,100)
count = 1
user = int(input("Guess a number from 1 to 100: "))
comp = int(input(f"\nIs ur number {c}\nIf its high write 0 \nIf its low write 2\nIf it is then write 1: "))
while comp != 1:
count += 1
if comp == 0:
b=c
c = (a + c) // 2
elif comp == 2:
a=c
c = (c + b) // 2
comp = int(input(f"\nIs ur number {c} \nif its high press 0 \nif its low press 2\nif its ur number press 1: "))
print(f"\nYour number was {user} and it took {count} turn to find ur number.")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.