0

如果我问了一个愚蠢的问题,我很抱歉,但我有点困惑......我一直在 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")

虽然手动测试它工作得很好,但在练习中有一些问题没有通过,主要是因为站点而不是不断猜测它是更高还是更低,有时它按下了错误的键并且我没有通过练习。

在尝试更改代码后,我无法完成课程,所以我看到了答案,这是我做错了,我应该使用布尔值来保持代码流畅,直到找到正确的数字。

我的问题是:我的代码错了吗?还有我做的任何错误阻止网站按正确的字母吗?只是好奇

非常感谢

4

2 回答 2

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
于 2013-10-26T04:17:51.243 回答
-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.")
于 2013-02-16T10:57:21.937 回答