如果我问了一个愚蠢的问题,我很抱歉,但我有点困惑。。。我一直在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")
虽然手工测试它效果很好,但在练习中有一些问题没有通过,主要是因为网站没有一直猜测它是高还是低,有时它按错了键,我没有通过练习。
在尝试更改代码后,我没能完成课程,所以我看到了答案,如果我做错了,我应该使用布尔值来保持代码的流动,直到它找到正确的数字。
我的问题是:我的代码错了吗?此外,我是否犯了任何错误,导致网站无法按正确的字母?只是好奇的
非常感谢
这是我今天终于解决的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
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.")