我的二分搜索算法有问题吗?

0 投票
2 回答
1350 浏览
提问于 2025-04-17 16:03

抱歉如果我问了个傻问题,但我有点困惑…… 我在edx上参加MIT6.00X课程,其中一个练习是用二分查找算法来找出秘密数字。我花了大约4个小时才完成这个练习(是的,我是个新手),但我成功写出了这个代码:

numGuesses = 0
lo = 0
hi = 100
mid = (hi + lo)/2
num = raw_input( "Input a number between 0 and 100 ")
if num > 0 or num < 100:
    while mid  != num:
        print ("Is your number " + str(mid) + "?")
        userinput = raw_input( "Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. ")

        if userinput == 'h':
            hi = mid
            mid = (hi + lo)/2
        elif userinput == 'l':
            lo = mid
            mid = (hi + lo)/2
        elif userinput == 'c':
            print ("Game over. Your secret number was:" + str(mid))
            break
        else:
            print ("Sorry, I did not understand your input.")
else:
    print ("You should use a number between 0 and 100")

在手动测试的时候,它运行得很好,不过在练习中有几个问题没通过,主要是因为网站有时候按错了键,而不是继续猜测数字是高还是低,这让我没能完成练习。

我尝试修改代码,但没能完成课程,所以我看了答案,这让我意识到我错在哪里,我应该使用一个布尔值来保持代码的运行,直到找到正确的数字。

我的问题是:我的代码真的那么错吗?还有我做的有什么错误导致网站按错字母吗?我只是好奇。

非常感谢

2 个回答

-1

在编程中,有时候我们需要把一些数据放到一个地方,方便我们后续使用。这个地方就像一个容器,可以存放不同类型的数据,比如数字、文字等等。

当我们想要从这个容器中取出数据时,我们需要知道这个数据的具体位置。就像在一个大箱子里找东西,我们需要记住东西放在哪里,才能快速找到它。

有些编程语言提供了工具,可以帮助我们更方便地管理这些数据,比如数组、列表等。它们就像是一个个小格子,可以把数据整齐地放在里面,方便我们随时取用。

总之,理解如何存放和取用数据是编程中的一个基本技能,掌握了这些,你就能更好地处理各种信息了。

lo = 0
hi = 100
mid = (hi + lo)/2
print 'Please think of a number between 0 and 100!'
while True:
    print ("Is your number " + str(mid) + "?")
    userinput = raw_input( "Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. ")

    if userinput == 'h':
        hi = mid
        mid = (hi + lo)/2
    elif userinput == 'l':
        lo = mid
        mid = (hi + lo)/2
    elif userinput == 'c':
        print ("Game over. Your secret number was:" + str(mid))
        break
    else:
        print ("Sorry, I did not understand your input.")
0

这是我今天终于解决的一个MITx的练习题。下面是我的解题方法:

print('Please think of an integers BETWEEN 0 and 100!')
#Define variable
x=100
low=0
high=x
ans=0
#Guessing code part
while ans<=x:
    print'Is your secret number:', str((low+high)/2), '?'
    s=raw_input("Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly:")
    if s!='h' and s!='l' and s!='c':
        print'Sorry I did not understand your input.'
    elif s=='h':
        high=(low+high)/2
    elif s=='l':
        low=(low+high)/2
    elif s=='c':
        print'Game over. Your secret number is:', str((low+high)/2)
        break

撰写回答