【问题标题】:Guess the number game optimization (user creates number, computer guesses)猜数字游戏优化(用户创建数字,电脑猜数字)
【发布时间】:2013-07-26 12:25:45
【问题描述】:

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

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

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!")

这是我上次跑步时发生的事情:

输入一个数字让计算机猜:78

计算机猜测... 74

计算机猜测... 89

计算机猜测... 55

计算机猜测... 78

电脑猜78,猜对了!

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

谢谢瑞恩海宁

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

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()

【问题讨论】:

  • 难道不应该反过来工作吗?电脑选数,用户猜?
  • 通常是这样,但是“艰巨的挑战”是切换程序的那个方面。让用户选择数字和计算机(AI)来猜测。
  • 嗨@mccdlibby,上面的任务在这里有一个关于Rosetta Code 的python 解决方案:rosettacode.org/wiki/Guess_the_number/… 如果你喜欢这个,你可能想看看“Bulls and cows task”,这是一个从这项任务取得进展。

标签: python algorithm python-3.x


【解决方案1】:

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

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)

【讨论】:

  • 其实不需要下限和上限变量...在问题的代码中,只需将guess = randint(1, 100)更改为guess = number,程序就会突然变得更短更简单。
【解决方案2】:

我简单地制作了你需要的游戏如下:

                  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("")

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

【讨论】:

  • 这个答案只是......不起作用,即使您尝试解决格式问题。
【解决方案3】:

你要找的是经典的binary search algorithm

def computer_guess(num):
    low = 1
    high = 100
    guess = (low+high)//2
    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()

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

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

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

这是一个示例运行

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!

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

  1. low = 1, high = 100 => guess = 50 50 low = 51
  2. low = 51, high = 100 => guess = 75 75 low = 76
  3. low = 76, high = 100 => guess = 88 88 > 82 所以high = 88
  4. low = 76, high = 88 => guess = 82 82 == 82 我们完成了。

注意这里的时间复杂度是O(lg(N))

【讨论】:

  • 我稍微改变了它,让计算机首先猜测是随机的,而不是总是 50。我导入了 randint() 函数。你有 random = 50 我改变了 random = randint(1,100) 我在 elif 语句之后移动了guess = (low+high)//2 - 这样计算机总是会猜测一个随机数,并且相同的约束保留到下一个猜测.
  • @mccdlibby 但是首先猜测一个随机数是次优的,您总是希望在每次猜测时减少一半可能的结果。如果您想优化,请将原始猜测保留为 50。Miklos Aubert 在下面发布了一个解决方案,该解决方案一直使用随机数。我们两个都有O(1) 的最佳案例。但我的最坏情况是O(lg(N)),而他的最坏情况是O(N)。为什么一开始要随机猜测?
  • 随机数真的没那么重要,我主要是想这样做,这样你就可以选择 50 作为一个数字,而不是立即猜测它。我确实明白你在说什么。
  • @mccdlibby 我想就“游戏”而言,这并不重要,我只是想确保您意识到这不是性能优势。
  • @Timo 是的,我想我可能试图让 OP 更清楚。它没有太大的区别,因为它会重新计算循环内的猜测。可能是guess = None。但谁知道我 7 年前在做什么
【解决方案4】:

这就是我的工作方式......

     __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.")

【讨论】:

    【解决方案5】:

    试试这个:

    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
    

    【讨论】:

      【解决方案6】:

      如果您使用本章中的内容(猜想这是来自 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!")
      

      【讨论】:

      • 该问题要求帮助进行搜索优化。您的代码从那回归到纯粹的猜测,这种方法已经在以前的帖子中介绍过。
      • 是的。但我通过谷歌搜索这个问题。如果其他人也这样做 - 我想帮助那个人。
      • @EugenioMParages 但是你是如何帮助那个人的?问题始于比纯粹猜测更好的代码。你的回答有什么贡献?
      【解决方案7】:

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

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

      max_guess_number = 0
      

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

      min_guess_number = 0
      

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

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

      4) 在“if computer_guess

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

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

      【讨论】:

        【解决方案8】:
        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"
        

        【讨论】:

        • 您的答案是我在这里找到的最好的答案。只需将下面的 rand 值转换为 int
        【解决方案9】:
        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**
        

        【讨论】:

        • 我的版本。尝试并幸运地让它工作。用户和电脑可以轮流猜测。每个尝试 5 次。
        【解决方案10】:
        import random 
        x = 1
        y = 99
        hads = random.randint(x,y)
        print (hads)
        javab = input('user id: ')
        while javab != 'd':
            if javab == 'b':
                x = hads
                hads = random.randint(x,y) 
                print(hads)
                javab = input('user id: ')   
            else:
                javab == 'k'
                y = hads
                hads = random.randint(x,y) 
                print(hads)
                javab = input('user id: ') 
        

        【讨论】:

        • 欢迎来到 SO。虽然这段代码 sn-p 可能是解决方案,但包含解释确实有助于提高帖子的质量。请记住,您是在为将来的读者回答问题,而这些人可能不知道您提出代码建议的原因。
        猜你喜欢
        • 2021-11-20
        • 1970-01-01
        • 2016-06-21
        • 2013-10-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多