我开始学习Python,并试图优化这个二分法搜索游戏。
high = 100
low = 0
guess = (high + low)/2
print('Please think of a number between 0 and 100!')
guessing = True
while guessing:
print('Is your secret number ' + str(guess) + '?')
pointer = 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 pointer == 'h':
high = guess
guess = (low + guess)/2
elif pointer == 'l':
low = guess
guess = (high + guess)/2
elif pointer == 'c':
guessing = False
else:
print('Sorry, I did not understand your input.')
print('Game over. Your secret number was: ' + str(guess))发布于 2013-02-22 00:44:11
我认为有些东西会改进您的代码,这是非常正确的:
high和low的变量,就不应该在开头的print中硬编码它们的值。//来确保得到整数除法。guess = (low + high) // 2作为while循环中的第一行,则只能编写一次。pointer时,您可能希望首先将其转换为小写,以确保h和H都被理解。format方法的str可以更清楚地显示您正在打印的内容。把这一切结合在一起:
high, low = 100, 0
print('Please think of a number between {0} and {1}!'.format(low, high))
guessing = True
while guessing:
guess = (low + high) // 2
print('Is your secret number {0}?'.format(guess))
pointer = 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.").lower()
if pointer == 'h' :
high = guess
elif pointer == 'l' :
low = guess
elif pointer == 'c':
guessing = False
else:
print('Sorry, I did not understand your input.')
print('Game over. Your secret number was {0}.'.format(guess))发布于 2013-02-22 16:15:21
除了Jaime的观点。
guessing标志,只需有一个带有break语句的无限循环。pointer是该变量的一个非常通用的名称,特别是因为它在其他编程语言中意味着其他一些东西。发布于 2015-09-07 10:31:15
在完成杰米的答复后,请注意:
键入'c'时,即使数字不是您所想的,始终打印代码print('Game over. Your secret number was {0}.'的这一部分。
因此,为了避免这种情况,还必须在(str(numbers) == str(guess))的分支上测试(response == 'c'):
high, low = 100, 0
guess = (low + high) // 2
numbers = raw_input('Please think of a number between {0} and {1}!'.format(low, high))
guessing = True
while guessing:
print('Is your secret number {0}?'.format(guess))
response = 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.").lower()
if response == 'h' :
high = guess
elif response == 'l' :
low = guess
elif (response == 'c') and (str(numbers) == str(guess)) :
print('Game over. Your secret number was {0}.'.format(guess))
break
else:
print('Sorry, I did not understand your input.')
guess = (low + high) // 2https://codereview.stackexchange.com/questions/22984
复制相似问题