猜数字游戏优化(用户创建数字,计算机猜测)

时间:2013-07-26 09:34:38

标签: python algorithm python-3.x

我是编程新手,所以我决定在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 ifif,else语句?

谢谢Ryan Haining

我使用了你回复中的代码并稍微改了一下,所以猜测总是随机的。如果您看到这个,请告诉我这是否是最好的方法。

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

10 个答案:

答案 0 :(得分:7)

您正在寻找的是经典的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()

算法的工作原理是选择一个低限和高限开始(在你的情况下,低= 1和高= 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 = 1high = 100 =&gt; guess = 50 50&lt; 82所以low = 51
  2. low = 51high = 100 =&gt; guess = 75 75&lt; 82所以low = 76
  3. low = 76high = 100 =&gt; guess = 88 88&gt; 82所以high = 88
  4. low = 76high = 88 =&gt; guess = 82 82 == 82我们已经完成了。
  5. 请注意,时间复杂度为O(lg(N))

答案 1 :(得分: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的数字。我希望这有帮助,只要问你是否需要更多信息。告诉我它是否有点毛病

答案 2 :(得分: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.")

答案 3 :(得分:1)

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

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

max_guess_number = 0

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

min_guess_number = 0

3)添加在&#34;如果computer_guess&gt; secret_number&#34;以下代码(我添加-1,以便计算机不会尝试猜测以前尝试过的数字):

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

4)在&#34;中加入以下代码:if computer_guess&lt; secret_number&#34;:

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

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

答案 4 :(得分: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)

答案 5 :(得分: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

答案 6 :(得分: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!")

答案 7 :(得分: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**

答案 8 :(得分: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: ') 

答案 9 :(得分:-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"