1

我对编程很陌生,所以大约 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()
4

10 回答 10

9

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

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 < 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 = 82 82 == 82 我们完成了。

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

于 2013-07-26T16:30:34.763 回答
1

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

                  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 的数字。我希望这会有所帮助,请问您是否需要更多信息。告诉我它是否有点小故障

于 2013-07-26T12:48:32.613 回答
1

我就是这样处理我的...

     __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.")
于 2014-04-04T06:37:25.410 回答
1

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

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 < secret_number”中添加如下代码:

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

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

于 2018-04-12T11:08:00.230 回答
1
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"
于 2018-07-06T07:15:51.443 回答
0

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

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)
于 2013-07-26T09:44:14.403 回答
0

尝试这个:

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
于 2015-04-13T10:45:15.987 回答
0

如果您使用本章中的内容(猜想这是来自 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!")
于 2016-03-04T01:18:37.207 回答
0
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: ') 
于 2020-06-06T21:37:27.267 回答
0
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**
于 2020-02-07T18:35:45.653 回答