gpt4 book ai didi

python - 参加 Python 类(class)并学习二分搜索,对为什么我的语义不正确感到困惑

转载 作者:太空宇宙 更新时间:2023-11-04 10:49:31 25 4
gpt4 key购买 nike

我们的任务是编写一段代码来猜测 0 到 100 之间的一个 secret 数字。这是我的一段代码:

low = 0
mid = 50
high = 100
secretnum = "Is your secret number " + str(mid) + "?"
print"Please think of a number between 0 and 100!"
print secretnum
herp = 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. ")
while herp != 'c':
if herp == 'h':
high = mid
mid = int((mid + low)/2)
elif herp == 'l':
low = mid
mid = int((mid + high)/2)
else:
print"Sorry, I did not understand your input."
print secretnum
herp = 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 herp == 'c':
print "Game over. Your secret number was: " + str(mid)

这是输出:

Is your secret number 50?
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. h
Is your secret number 50?
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. l
Is your secret number 50?
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. c
Game over. Your secret number was: 37

最佳答案

正如 Raufio 指出的那样,Python 字符串是不可变的。要解决一遍又一遍地重复 50 的问题,您需要在打印出问题时再次调用 str(mid)。例如:

low = 0
mid = 50
high = 100
secretnum = "Is your secret number: "
print"Please think of a number between 0 and 100!"
print secretnum + str(mid) + "?"
herp = 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. ")
while herp != 'c':
if herp == 'h':
high = mid
mid = int((mid + low)/2)
elif herp == 'l':
low = mid
mid = int((mid + high)/2)
else:
print"Sorry, I did not understand your input."
print secretnum + str(mid) + "?"
herp = 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 herp == 'c':
print "Game over. Your secret number was:", mid

关于python - 参加 Python 类(class)并学习二分搜索,对为什么我的语义不正确感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14845083/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com