我的Bisection搜索算法错了吗?

时间:2013-02-16 00:39:38

标签: python algorithm

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

答案 0 :(得分: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

答案 1 :(得分:-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.")