Python 猜数游戏优化(用户创号,电脑猜)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17877870/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 09:23:56  来源:igfitidea点击:

Guess the number game optimization (user creates number, computer guesses)

pythonalgorithmpython-3.x

提问by mccdlibby

I am very new to programming so I decided to start with Python about 4 or 5 days ago. I came across a challenge that asked for me to create a "Guess the number" game. After completion, the "hard challenge" was to create a guess the number game that the user creates the number and the computer (AI) guesses.

我对编程很陌生,所以我决定在大约 4 或 5 天前开始使用 Python。我遇到了一个挑战,要求我创建一个“猜数字”游戏。完成后,“硬挑战”是创建一个猜数字游戏,用户创建数字和计算机(AI)猜测。

So far I have come up with this and it works, but it could be better and I'll explain.

到目前为止,我已经提出了这个并且它有效,但它可能会更好,我会解释。

from random import randint

print ("In this program you will enter a number between 1 - 100."
       "\nAfter the computer will try to guess your number!")

number = 0

while number < 1 or number >100:
    number = int(input("\n\nEnter a number for the computer to guess: "))
    if number > 100:
        print ("Number must be lower than or equal to 100!")
    if number < 1:
        print ("Number must be greater than or equal to 1!")

guess = randint(1, 100)

print ("The computer takes a guess...", guess)

while guess != number:
    if guess > number:
        guess -= 1
        guess = randint(1, guess)
    else:
        guess += 1
        guess = randint(guess, 100)
    print ("The computer takes a guess...", guess)

print ("The computer guessed", guess, "and it was correct!")

This is what happened on my last run:

这是我上次运行时发生的情况:

Enter a number for the computer to guess: 78

输入一个数字让电脑猜:78

The computer takes a guess... 74

计算机需要猜测... 74

The computer takes a guess... 89

计算机需要猜测... 89

The computer takes a guess... 55

计算机需要猜测... 55

The computer takes a guess... 78

计算机需要猜测... 78

The computer guessed 78 and it was correct!

电脑猜到了78,而且是对的!

Notice that it works, however when the computer guessed 74, it then guessed a higher number to 89. The number is too high so the computer guesses a lower number, however the number chosen was 55. Is there a way that I can have the computer guess a number that is lower than 89, but higher than 74? Would this require additional variables or more complex if, elif, else statements?

注意它是有效的,但是当计算机猜到 74 时,它又猜到了一个更大的数字到 89。这个数字太高了,所以计算机猜到了一个较低的数字,但是选择的数字是 55。有没有办法让我得到计算机猜一个小于 89 但大于 74 的数字?这是否需要额外的变量或更复杂的 if、elif、else 语句?

Thank you Ryan Haining

谢谢瑞恩海宁

I used the code from your reply and altered it slightly so the guess is always random. If you see this, let me know if this is the best way to do so.

我使用了您回复中的代码并稍作修改,因此猜测始终是随机的。如果你看到这个,请告诉我这是否是最好的方法。

from random import randint

def computer_guess(num):
    low = 1
    high = 100
    # This will make the computer's first guess random
    guess = randint(1,100)
    while guess != num:
        print("The computer takes a guess...", guess)
        if guess > num:
            high = guess
        elif guess < num:
            low = guess + 1
        # having the next guess be after the elif statement
        # will allow for the random guess to take place
        # instead of the first guess being 50 each time
        # or whatever the outcome of your low+high division
        guess = (low+high)//2    

    print("The computer guessed", guess, "and it was correct!")


def main():
    num = int(input("Enter a number: "))
    if num < 1 or num > 100:
        print("Must be in range [1, 100]")
    else:
        computer_guess(num)

if __name__ == '__main__':
    main()

采纳答案by Ryan Haining

what you are looking for is the classic binary search algorithm

您正在寻找的是经典的二分搜索算法

def computer_guess(num):
    low = 1
    high = 100
    guess = 50
    while guess != num:
        guess = (low+high)//2
        print("The computer takes a guess...", guess)
        if guess > num:
            high = guess
        elif guess < num:
            low = guess + 1

    print("The computer guessed", guess, "and it was correct!")


def main():
    num = int(input("Enter a number: "))
    if num < 1 or num > 100:
        print("Must be in range [1, 100]")
    else:
        computer_guess(num)

if __name__ == '__main__':
    main()

The algorithm works by selecting a low and high limit to start with (in your case low=1 and high=100). It then checks the midpoint between them.

该算法的工作原理是选择一个下限和上限(在您的情况下为 low=1 和 high=100)。然后检查它们之间的中点。

If the midpoint is less than number, the midpoint becomes the new lower bound. If the midpoint is higher, it becomes the new upper bound. After doing this a new midpoint is generated between the upper and lower bound.

如果中点小于 number,则中点成为新的下限。如果中点更高,则它成为新的上限。执行此操作后,将在上限和下限之间生成一个新的中点。

To illustrate an example let's say you're looking for 82.

为了举例说明,假设您正在寻找 82。

Here's a sample run

这是一个示例运行

Enter a number: 82
The computer takes a guess... 50
The computer takes a guess... 75
The computer takes a guess... 88
The computer takes a guess... 82
The computer guessed 82 and it was correct!

So what's happening here in each step?

那么这里的每一步都发生了什么?

  1. low = 1, high = 100=> guess = 5050 < 82 so low = 51
  2. low = 51, high = 100=> guess = 7575 < 82 so low = 76
  3. low = 76, high = 100=> guess = 8888 > 82 so high = 88
  4. low = 76, high = 88=> guess = 8282 == 82 and we're done.
  1. low = 1, high = 100=> guess = 5050 < 82 所以low = 51
  2. low = 51, high = 100=> guess = 7575 < 82 所以low = 76
  3. low = 76, high = 100=> guess = 8888 > 82 所以high = 88
  4. low = 76, high = 88=> guess = 8282 == 82 我们就完成了。

Note that the time complexity of this is O(lg(N))

请注意,它的时间复杂度为 O(lg(N))

回答by Miklos Aubert

You only need two new variables to keep track of the low and high limits :

您只需要两个新变量来跟踪上下限:

low = 1
high = 100
while guess != number:
    if guess > number:
        high = guess - 1
    else:
        low = guess + 1
    guess = randint(low, high)
    print ("The computer takes a guess...", guess)

回答by Miklos Aubert

I briefly made the game which you need with follows:

我简要地制作了您需要的游戏,如下所示:

                  import random

                  guess=int(input("Choose a number you want the computer to guess from  1-100: "))

                  turns=0
                  a=None

                  compguess=random.randint(1,100)

                 while turns<10 and 100>guess>=1 and compguess!=guess: #computer has 10 turns to guess number, you can change it to what you want
                  print("The computer's guess is:  ", compguess)
                  if compguess>guess:
                   a=compguess
                   compguess=random.randint(1,compguess)

                 elif compguess<guess:
                  compguess=random.randint(compguess,a)
                  turns+=1


               if compguess==guess and turns<10:
                print("The computer guessed your number of:" , guess)
                turns+=1

              elif turns>=10 and compguess!=guess:
               print("The computer couldn't guess your number, well done.")


             input("")

This is a bit rusty, but you could improve it by actually narrowing down the choices so the computer has a greater chance of guessing the right number. But where would the fun in that be? Notice how in my code, if the computer guesses a number which is greater than than the number the user has inputed, it will replace 100 from the randint function with that number. So if it guesses 70 and its too high, it won't choose a number greater than 70 after that. I hope this helps, just ask if you need any more info. And tell me if it's slightly glitchy

这有点生疏,但您可以通过实际缩小选择范围来改进它,以便计算机有更大的机会猜测正确的数字。但这其中的乐趣在哪里呢?请注意在我的代码中,如果计算机猜测的数字大于用户输入的数字,它将用该数字替换 randint 函数中的 100。因此,如果它猜测 70 并且它太高,则在此之后它不会选择大于 70 的数字。我希望这会有所帮助,请问您是否需要更多信息。告诉我它是否有点小故障

回答by Ghengis Yan

This is how I went about mine...

这就是我如何处理我的...

     __author__ = 'Ghengis Yan'

     print("\t This is the age of the computer")
     print("\n The computer should impress us... the Man")

     import random

     #User chooses the number
     the_number = int(input("Human Choose a number between 0 and 100 "))
     tries = 1
     computer = random.randint(0,100)
     # User choose again loop
     while the_number > 100:
         the_number = int(input("I thought Humans are smarter than that... \nRetype the number... "))
     if the_number <= 100:
         print("Good")

     # Guessing Loop
     while computer != the_number:
         if computer > the_number:
             print(computer, "lower... Mr. Computer")
         else:
             print(computer, "higher... Mr. Computer")
         computer = int(random.randint(0,100))
         tries += 1

     print("Computer Congratulations... You beat the human! The Number was ", the_number)
     print("It only took a computer such as yourself", tries, "tries to guess it right...          pathetic")
     input("\nPress the enter key to exit.")

回答by buba

Try this:

尝试这个:

import random


player = int(input("tap any number: "))
comp = random.randint(1, 100)
print(comp)

comp_down = 1
comp_up = 100

raw_input("Press Enter to continue...")


while comp != player:
   if comp > player:
    comp_up = comp - 1
    comp = random.randint(comp_down, comp_up)
    print(comp)
   if comp < player:
    comp_down = comp + 1
    comp = random.randint(comp_down, comp_up)
    print(comp)
   if comp == player:
       break

回答by Eugenio M Parages

If you use the stuff in the chapter (guessing this is from the Dawson book) you can do it like this.

如果您使用本章中的内容(猜测这是来自 Dawson 的书),您可以这样做。

import random
#program allows computer to guess my number
#initial values
user_input1=int(input("Enter number between 1 and 100: "))
tries=1
compguess=random.randint(1, 100)

#guessing loop
while compguess != user_input1:
    if compguess > user_input1:
        print("Lower Guess")
        compguess=random.randint(1, 100)
        print(compguess)
    elif compguess < user_input1:
        print("Higher Guess")
        compguess=random.randint(1, 100)
        print(compguess)

        tries += 1 #to have program add up amount of tries it takes place it in the while block

print("Good job Computer! You guessed it! The number was,", user_input1, \
      " and it only took you", tries, " tries!")

回答by askepott

What I did for the same challenge was:

我为同样的挑战所做的是:

1) Define a variable that records the max value input by guessing computer. Ex:

1) 定义一个变量,记录猜测计算机输入的最大值。前任:

max_guess_number = 0

2) Define another variable with the lowest guessed value. Ex.

2) 定义另一个具有最低猜测值的变量。前任。

min_guess_number = 0

3) Added in the "if computer_guess > secret_number" clause the following code (I added -1 so that the computer wouldn't try to guess the already previously tried number):

3) 在“if computer_guess > secret_number”子句中添加了以下代码(我添加了 -1 以便计算机不会尝试猜测已经尝试过的数字):

max_guess_number = guess - 1
computer_guess = random.randint(min_guess_number, max_guess_number)

4) Added the following code in the "if computer_guess < secret_number":

4) 在“if computer_guess < secret_number”中添加如下代码:

min_guess_number = guess + 1
computer_guess = random.randint(min_guess_number, max_guess_number)

Worth noting is the fact that I set my while loop to loop until another variable "guess_status" changes into a value 1 (the default I set to 0). This way I actually saw the result when the while loop finished.

值得注意的是,我将 while 循环设置为循环,直到另一个变量“guess_status”变为值 1(我设置为 0 的默认值)。这样,当 while 循环完成时,我实际上看到了结果。

回答by danieldivinagracia

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

回答by Edward

import random

corr_num = random.randint(1,100)

player_tries = 0
com_tries = 0

while player_tries <5 and com_tries < 5:
    player = int(input("player guess is "))
    if player > corr_num:
    print("too high")
    player_tries +=1

if player < corr_num:
    print("too low")
    player_tries +=1

if player == corr_num:
    print("Player wins")
    break

computer = random.randint(1,100)
print("computer guess is ", computer)

if computer > corr_num:
    print("too high")
    com_tries = 0

if computer < corr_num:
    print("too low")
    com_tries = 0

if computer == corr_num:
    print ("computer wins")
    break

else:
print("Game over, no winner")**strong text**