这个练习基于一个猜谜游戏,用户(你)输入一个下限和上限int,然后PC在这些边界内选择一个随机数。你的工作是猜测(最好是在中间),程序会告诉用户你的猜测是大于、小于或等于电脑选择的数字。记录尝试次数。
代码如下:
import random smaller = int(input("Enter the smaller number: ")) larger = int(input("Enter the larger number: ")) myNumber = random.randint(smaller, larger) count = 0 while True: count += 1 userNumber = int(input("Enter your guess: ")) if userNumber < myNumber: print("Too small!") elif userNumber > myNumber: print("Too large!") else: print("Congratulations! You've got it in", count, "tries!") break
以下是示例输出:
#Output example Enter the smaller number: 1 Enter the larger number: 100 Enter your guess: 50 Too small! Enter your guess: 75 Too large! Enter your guess: 63 Too small! Enter your guess: 69 Too large! Enter your guess: 66 Too large Enter your guess: 65 You've got it in 6 tries!
下面是练习说明:
修改猜谜游戏程序,让用户想到计算机必须猜的数字。
计算机的猜测次数不得超过最小值,并且必须防止用户通过输入误导性提示来作弊。
使用I'm out of guesses, and you cheated
和Hooray, I've got it in X tries
作为最终输出。
(提示:使用math.log
函数计算输入下限和上限后所需的最小猜测次数。)“
以下是我应该能够复制的两个示例输出:
Enter the smaller number: 0 Enter the larger number: 10 0 10 Your number is 5 Enter =, <, or >: < 0 4 Your number is 2 Enter =, <, or >: > 3 4 Your number is 3 Enter =, <, or >: = Hooray, I've got it in 3 tries!
和
Enter the smaller number: 0 Enter the larger number: 50 0 50 Your number is 25 Enter =, <, or >: < 0 24 Your number is 12 Enter =, <, or >: < 0 11 Your number is 5 Enter =, <, or >: < 0 4 Your number is 2 Enter =, <, or >: < 0 1 Your number is 0 Enter =, <, or >: > 1 1 Your number is 1 Enter =, <, or >: > I'm out of guesses, and you cheated!
现在是我的代码:
from math import log2 #get the lower and upper bounds that the PC can guess between smaller = int(input("Enter the smaller number: ")) larger = int(input("Enter the larger number: ")) #this should calculate the maximum number of tries the PC can do max_tries = round(log2(larger-smaller+1)) print("PC should guess in no more than %s tries\n" % max_tries) count = 0 while count <= max_tries: count += 1 pc_guess = (larger+smaller) // 2 #This is the PC's guess print("%d %d" % (smaller, larger)) #boundry print("Your number is ", pc_guess) #printing PC's guess op = input("Enter =, <, or >: ") #giving PC more info if op == '<': larger = pc_guess - 1 elif op == '>': smaller = pc_guess + 1 elif op == '=': print("Hooray I've got it in", count, "tries")#PC guessing correct break if count > max_tries: print("I'm out of guesses, and you cheated")
我对这个练习的思考是否正确?
Furthermore, I don't underst和 how to get the PC to get the right answer in "no more than the minimum number of guesses," which I calculated as log2(larger-smaller+1)
in my code. Calculating the average of the upper 和 lower bound still results in greater tries than the log2 result.
此外,我是否正确计算了电脑的最佳猜测(平均计算)?