所以..我已经了解了二分搜索及其工作原理,甚至在没有用户任何输入的情况下使用常量数组进行了尝试,但现在我尝试应用向量而不是数组来让用户输入两个列表的值从向量中搜索数字和要搜索的目标。 在这里,我在使用数组时使用了普通的分治法 我的问题是我使用 vector 做了几乎相同的方法,但它显示了无限量的 ...
提示:本站收集StackOverFlow近2千万问答,支持中英文搜索,鼠标放在语句上弹窗显示对应的参考中文或英文, 本站还提供 中文繁体 英文版本 中英对照 版本,有任何建议请联系yoyou2525@163.com。
我正在尝试使用二分搜索制作猜谜游戏
这是我的代码:
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()
我面临的问题是二分搜索
例如:
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
它找到了我不想要的从 0 到 61 的中间数字
我想要的是找到 22 的中间数字,如下所示:
(22 + 61) // 2 导致它给我们 41
then (41 + 61) // 2 导致它打印 51
then (51 + 61) // 2 导致它打印 56
then (56 + 51 ) // 2 导致它打印 53
then (53 + 56 ) // 2 导致它打印 54
then (54 + 56 ) // 2 导致它打印 55
55 这是我们的猜测数字
我对您的函数进行了以下修改,以缩小itprorh66建议的研究间隔。 代码如下:
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.