让计算机猜测一个用户在不超过 10 次的情况下在 1 到 1000 之间选择的数字。此分配使用一种称为二分搜索的算法。每次猜测后,该算法将搜索的可能答案数量减半。完整程序的伪代码如下;你的任务是把它变成一个工作的python程序。该程序应该首先在屏幕上打印指令,说明用户应该选择一个介于 1 到 1000 之间的数字,计算机将在不超过 10 次尝试中猜出它。然后它开始猜测,并在每次猜测后询问用户反馈。如果猜测需要更低,则应指示用户输入 -1,如果正确则输入 0,如果需要更高则输入 1。当程序猜测正确时,它应该报告需要猜测的次数。
伪代码
- Print instructions to the user
-Start with high = 1000, low = 1, and tries = 1
- While high is greater than low
- Guess the average of high and low
- Ask the user to respond to the guess
- Handle the four possible outcomes:
- If the guess was right, print a message that tries guesses were required and quit the program
- If the guess was too high, set high to one less than the guess that was displayed to the user and increment tries
- If the guess was too low, set low to one more than the guess that was displayed to the user and increment tries
- If the user entered an incorrect value, print out the instructions again
- high and low must be equal, so print out the answer and the value of tries
我需要一些认真的帮助!我根本不明白这些东西!这就是我所拥有的
def main(x, nums, low, high):
input("Enter -1 if the guess needs to be lower, 0 if the guess was right, or 1 if the guess needs to be higher: ")
for i in range (1, 1001):
main()
我什至不知道它是否正确!