Python数字游戏反向

时间:2015-06-19 09:39:35

标签: python

所以我必须做一个"游戏"在python上,我想到一个数字,它试图猜测数字。我必须告诉它它是否高于或低于它猜测的数字并从那里继续。到目前为止,我有它做我需要的但我不知道如何使python记住它猜测的数字。因此,如果我告诉它猜测1到10之间的数字并猜测7,我说它太高了,然后猜测4,我说它太低了,它可能会猜到8。好吧我因为我说它已经低于7,所以不能猜测高于7的数字。有没有办法让它记住? 这是我的代码:

from random import randrange
def lowHigh():
    l = input ("Please input the low number range.")
    numl = eval(l)
    h = input ("Please input the high number range.")
    numh = eval(h)
    guess = randrange(1,numh + 1)
    print (guess)
    while True:
        ask = input("Is this number correct? y for yes or n for no.")
        if ask == 'y':
            print("Yay! I guessed right!")
            break
        else:
            lowOrHigh = input ("Is this number too high or low? h for high, l for low.")
            if lowOrHigh == 'h':
                guess = randrange(numl,guess-1)
                print(guess)
            else:
                guess = randrange(guess+1,numh)
                print(guess)

4 个答案:

答案 0 :(得分:2)

您可以使用两个不同的数字来表示最低和最高的猜测。

当计算机猜出一个数字及其较高的实际数字时,您可以设置最高=该数字。

当计算机猜出一个数字及其低于实际数字时,你可以使用更低的=那个数字。

每次只在这两个最低和最高数字之间取随机数。

代码看起来像 -

from random import randrange
def lowHigh():
    l = input ("Please input the low number range.")
    numl = eval(l)
    h = input ("Please input the high number range.")
    numh = eval(h)
    lowest = l
    highest = h
    while True:
        guess = randrange(lowest,highest+1)
        print (guess)
        ask = input("Is this number correct? y for yes or n for no.")
        if ask == 'y':
            print("Yay! I guessed right!")
            break
        else:
            lowOrHigh = input ("Is this number too high or low? h for high, l for low.")
            if lowOrHigh == 'h':
               highest = guess - 1
            else:
               lowest = guess

答案 1 :(得分:1)

您可以将其猜测的数字保存在列表中,然后检查列表中是否已有新猜测。 像这样初始化一个空列表:

guessed=[]

然后你可以将程序的猜测附加到列表中

guessed.append(guess)

答案 2 :(得分:0)

<强>演示:

from random import randrange
import time


def guessNumber(min_no, max_no):
    """ Select number from the range. """
    try:
        return randrange(min_no, max_no)
    except ValueError:
        return min_no


def userNoInput(msg):
    """ Get Number into from the user. """
    while 1:
        try:
            return int(raw_input(msg))
        except ValueError:
            print "Enter Only Number string."
            continue

def findMe():
    """ 
        1. Get Lower and Upeer Value number from the User.
        2. time sleep to guess number for user in between range.
        3. While infinite loop.
        4. Get guess number from the Computer.
        5. User can check guess number and tell computer that guess number if correct ror not.
        6. If Correct then print msg and break While loop.
        7. If not Correct then 
             Ask Computer will User that guess number is Greate or Lower then Actual number. 
            7.1. If Greater then Set Max limit as guess number.  
            7.2. If Not Greater then Set Min limit as guess number.
            7.3. Continue While loop
    """
    min_no = userNoInput("Please input the low number range:")
    max_no = userNoInput("Please input the high number range:")
    print "Guess any number between %d and %d."%(min_no, max_no)
    max_no += 1
    time.sleep(2)


    while True:
        guess = guessNumber(min_no, max_no)
        print "Computer guess Number:-", guess
        ask = raw_input("Is this number correct? y for Yes or n for No:")
        if ask.lower() == 'y':
            print("Yay! I guessed right!")
            break
        else:
            lowOrHigh = raw_input("Is this number too high or low? h for high, l for low.")
            if lowOrHigh.lower() == 'h':
                #- As guess number is higher then set max number to guess number. 
                max_no = guess
            else:
                #- As guess number is lower then set min number to guess number. 
                min_no = guess

findMe()

输出:

Please input the low number range:10
Please input the high number range:20
Guess any number between 10 and 20.
Computer guess Number:- 14
Is this number correct? y for Yes or n for No:n
Is this number too high or low? h for high, l for low.l
Computer guess Number:- 19
Is this number correct? y for Yes or n for No:n
Is this number too high or low? h for high, l for low.h
Computer guess Number:- 17
Is this number correct? y for Yes or n for No:n
Is this number too high or low? h for high, l for low.h
Computer guess Number:- 16
Is this number correct? y for Yes or n for No:n
Is this number too high or low? h for high, l for low.h
Computer guess Number:- 15
Is this number correct? y for Yes or n for No:y
Yay! I guessed right!

注意:

Python 2.7:raw_input()方法,print是语句。

Python 3.X:input()方法,print是函数。

答案 3 :(得分:0)

  

它非常类似于二进制搜索算法

只是这些算法中通常的中间值可以被randrange(Low,High)

取代

我不确定这是否是一个正常工作的代码,但我建议你递归执行:

items= range(l,h)
def random_search(ask, items, l, h):
    """
    Random search function.
    Assumes 'items' is a sorted list.
    The search range is [low, high)
    """
    ask = input("Is this number correct? y for yes or n for no.")
    lowOrHigh = input ("Is this number too high or low? h for high, l for low.")
    elem = randrange(l,h)

    if ask == 'y':
        return elem
    elif h == l:
        return False
    elif lowOrHigh == 'h':
        items= range(l,elem)
        return random_search(ask, items, l, elem)
    else:
        items= range(elem, h)
        return random_search(ask, items, elem, h)