猜数字游戏 Python 二分查找
我搞不清楚我的代码哪里出问题了。我想让用户想一个1到100之间的数字,然后这个程序能猜到这个数字。程序会把范围内的最高和最低数字加起来,然后除以2,得到一个猜测的数字。用户如果觉得程序猜的数字比他们的数字大,就输入1;如果小,就输入-1;如果猜对了,就输入0。最多猜7次,应该能猜对这个数字。但是我运行代码时,它总是猜50,而且从来不改变。看起来好像没有执行到if语句。程序应该在运行中找到新的猜测。
def main():
import random
print("Guessing Game")
print("")
print("Think of a number 1 and 100 inclusive.\nAnd I will guess what it is in 7 tries or less.")
print("")
ready = input("Are you ready? (y/n): ")
print("")
if ready != "y" and ready != "n":
ready = input("Are you ready? (y/n): ")
if ready == "n":
print("Bye")
if ready == "y":
lo = 0
hi = 100
guess_high = 1
guess_same = 0
guess_low = -1
a = random.randint(1,100)
num_list = []
for i in range(1,100):
num_list.append(i)
while (lo <= hi):
guess_count = 0
for guess_count in range(1,8):
guess_count += 1
guess = (lo + hi) // 2
print("Guess",guess_count," : The number you thought was",guess)
user_response = input("Enter 1 if my guess was high, -1 if low, and 0 if correct: ")
if (user_response == 1):
hi = guess - 1
guess_count += 1
guess = (lo + hi) // 2
elif (user_response == -1):
lo = guess + 1
guess_count += 1
guess = (lo + hi) // 2
elif (user_response == 0):
print("Thank you for playing the Guessing Game.")
main()
1 个回答
2
你主要的问题出现在第29、30、34和38行:input()
返回的是一个字符串,但你却在和一个整数比较。"1"
和 1
是不相等的!
还有一些其他问题:
第2行:
import random
不应该放在main()
函数里面。第7到10行:获取
ready
的是/否回答应该放在一个while
循环里,或者更好的是,放在一个单独的函数中——重复直到得到有效的回答。第9、11、13行:你需要了解一下
else
和elif
的用法。第14行:应该是
lo = 1
。第19行:
a
是干什么的?你根本没有用到它。第20到22行:你不需要记录每一个可能的数字,只需要记录最低和最高的值,这些你已经有了(
lo
和hi
),如果你真的需要的话,可以用num_list = list(range(1, 100))
来生成。第25、26、32、36行:增加
guess_count
是没用的,因为每次重新进入for
循环时它都会被重置。
这里有一个整理过的版本:
# assumes Python 3
def get_yn(prompt, yes_values={"y", "yes"}, no_values={"n", "no"}):
"""
Prompt for a yes or no response;
return True for yes or False for no
"""
while True:
response = input(prompt).strip().lower()
if response in yes_values:
return True
elif response in no_values:
return False
def get_int(prompt, lo=None, hi=None):
"""
Prompt for a number,
return as int
"""
while True:
try:
value = int(input(prompt))
if (lo is None or lo <= value) and (hi is None or value <= hi):
return Value
except ValueError:
pass
def get_one_of(prompt, values):
"""
Prompt for a response in values,
return response string
"""
while True:
value = input(prompt).strip().lower()
if value in values:
return value
def main():
print(
"Guessing Game\n"
"\n"
"Think of a number in [1..100],\n"
"and I will try to guess it in no more than 7 tries.\n"
)
if get_yn("Are you ready? (y/n): "):
lo, hi = 1, 100
got_it = False
for attempt in range(1, 8):
guess = (lo + hi) // 2
print("I guess {}!".format(guess))
res = get_one_of("Was this [L]ow, [H]igh, or [C]orrect? ", {"l", "h", "c"})
if res == "l":
lo = guess + 1
elif res == "h":
hi = guess - 1
else: # correct!
got_it = True
break
if lo > hi:
break
if got_it:
print("Ha! Got it in {} guesses!".format(attempt))
else:
print("Something smells in the state of Denmark...")
else:
print("Bye!")
if __name__=="__main__":
main()