合理猜测给定范围内的所选数字

时间:2015-09-17 11:20:00

标签: python

有任务:

  

玩家选择1到100之间的随机数,计算机必须猜测。在开始之前,先想想你的猜测方式。如果一切顺利,请尝试编写游戏代码。

我的代码是:

import random
num = int(input('Your number: '))
numC = random.randint(1, 100)
tries = 1
while numC != num:
    numC = random.randint(1, 100)
    if numC > num:
        print(numC, 'Less')
        numC = random.randint(1, numC)
    else:
        print(numC, 'More')
        numC = random.randint(numC, 100)
    tries += 1
print(numC, 'Computer guessed your number with', tries, 'tries')

它有效,但我认为它不像作者想要的那样有用。

如何使用少数尝试使此程序猜测数字?我知道它是关于减少随机生成器的帧,但我不知道如何在不使用无限数量的变量的情况下做到这一点。

4 个答案:

答案 0 :(得分:3)

我改变这种方式,动态记住范围并猜测正确的范围

import random
num = int(input('Your number: '))
numC = random.randint(1, 100)
tries = 1
lowerLimit=1
upperLimit=100
while numC != num:
  if numC > num:
    print(numC, 'Less')
    upperLimit = numC+1
  else:
    print(numC, 'More')
    lowerLimit = numC-1
  tries += 1
  numC = random.randint(lowerLimit, upperLimit)
print(numC, 'Computer guessed your number with', tries, 'tries')

答案 1 :(得分:1)

我有个主意,您对此有何看法?

import random
num = int(input('Your number: '))
tries = []
numC = random.randint(1, 100)
while numC != num:
    numC = random.randint(1, 100)
    if numC in tries:
        pass
    elif numC > num:
        print(numC, 'Less')
        tries.append(numC)
    elif numC < num:
        print(numC, 'More')
        tries.append(numC)
print(numC, 'Computer guessed your number with', len(tries), 'tries')

答案 2 :(得分:0)

我试过,但我的程序只能猜测用户是否告诉计算机计算机的猜测是高于还是低于用户的数字。我还添加了各种其他东西,使其更加用户友好。无论如何它在这里:

def bp(x): if '.' in str(x): tenth=int(str(x).split('.')[1][0]) if tenth<=4: return str(x).split('.')[0] else: return int(str(x).split('.')[0])+1 else: return x guess=50 low=0 high=100 rep=0 while rep<=10: try: reply=input('Is the number %s? (Y/H/L)\n'%guess) except IndexError: continue if reply=='y': print('Haha!') break elif reply=='l': low=guess elif reply=='h': high=guess else: print("Enter 'Yes', 'Low', or 'High'") continue rep+=1 guess=bp((int(low)+int(high))/2) break

答案 3 :(得分:0)

避免猜测特定范围内的数字怎么样? 只需使用binary search作为评论告诉,然后从猜测50开​​始。

import random

num = int(input('Your number: '))
tries = 1
lowerLimit = 1
upperLimit = 100
numC = 50

while numC != num:
    if numC > num:
        print(numC, 'Less')
        upperLimit = numC
    else:
        print(numC, 'More')
        lowerLimit = numC
    tries += 1
    numC = lowerLimit + (upperLimit - lowerLimit) / 2

print(numC, 'Computer guessed your number with', tries, 'tries')

你可以期待7次尝试的最坏情况运行时间。

runtime