从小于变量

时间:2016-11-15 15:49:10

标签: python python-3.x

我还很早就开始学习编码,如果代码不稳定,那就很抱歉...... 我正在根据用户给出的两个数字的第一个猜测猜测一个数字猜谜游戏,然后将这些数字放入升序列表中。那么我的问题,我想从我的第一次猜测中删除更低/更高的数字然后只需执行random.choice(list)代码....

import random
print("\nLets see if I can guess the number you're thinking.\nI've got some questions first")
tryNumber=1
trys=int(input("How many trys will you let me have? "))
numberRangeLow=int(input("What is the lowest number I can guess?: "))
numberRangeHigh=int(input("And the highest?: "))

print("\nSo I have",str(trys),"trys")
print("And the number is between",str(numberRangeLow),"and",str(numberRangeHigh)+".\n")
firstGuess=random.randint(numberRangeLow, numberRangeHigh)
numbers=[]
nums=[]
while numberRangeLow < numberRangeHigh+1:
    numbers.append(numberRangeLow)
    nums.append(numberRangeLow)
    numberRangeLow+=1 

while tryNumber < trys:
    print("Is your number", str(firstGuess), "?")
    answer=input("Enter 'higher', 'lower' or correct (Case-Sensitive)")
    if answer == "higher":
        numbers.remove('''nums >= firstGuess''')
        firstGuess=random.choice(numbers)
        print("Is your number", str(firstGuess), "?")

我对功能感到不舒服,这就是为什么它如此之多。一旦我完全病了,就把它改成调用整个事物的功能。 -hopefully -

2 个答案:

答案 0 :(得分:0)

numbers.remove('''nums >= firstGuess''')更改为numbers.remove(firstGuess)您还需要考虑大于您第一次猜测的数字,因此您必须删除之前的数字。 numbers = ([x for x in numbers if x > firstGuess])应该做到这一点。

while tryNumber < trys:
    print("Is your number", str(firstGuess), "?")
    answer=input("Enter 'higher', 'lower' or correct (Case-Sensitive)")
    if answer == "higher":
      numbers = ([x for x in numbers if x > firstGuess])
      firstGuess=random.choice(numbers)

这应该让你开始。

答案 1 :(得分:0)

首先,while numberRangeLow < numberRangeHigh+1: do stuffrange基本相同。
对于相同的结果,您可以使用numbers = range(numberRangeLow, numberRangeHigh + 1),这将为您构建列表。

如果您使用str.lower()它自动将其置于小写状态,您也不需要警告其区分大小写。例如,您可以执行if answer.lower() == "higher"

要删除号码,您可以执行list slicing。例如,如果您有a = [1, 2, 3, 4],并且它低于3,则可以使用a.index(3)获得3的索引,在这种情况下,它将给出2。然后,使用a[2:]切断高于此索引的任何内容,您已删除任何高于3的数字。

这里有一个快速更新你的代码做我提到的位。

trys=int(input("How many trys will you let me have? "))
numberRangeLow=int(input("What is the lowest number I can guess?: "))
numberRangeHigh=int(input("And the highest?: "))
print("\nSo I have",str(trys),"trys")
print("And the number is between",str(numberRangeLow),"and",str(numberRangeHigh)

#New bits:
numbers = range(numberRangeLow, numberRangeHigh + 1)
for i in range(trys):
    guess = random.choice(numbers)
    print("Is your number", str(guess), "?")
    answer = input("Enter 'higher', 'lower' or 'correct'").lower()
    if answer == 'correct':
        break
    elif answer == 'higher':
        list_index = numbers.index(guess)
        numbers = numbers[list_index + 1:]
    elif answer == 'lower':
        list_index = numbers.index(guess)
        numbers = numbers[:list_index]

我重新排列了代码的最后一部分,因此您没有随机选择的2个副本。另外,对于记录,它被视为name_variables_like_thisnotLikeThis的更好做法。

编辑:Kevins的方式与我的略有不同,一个简单的比较就是假设你已经将数字写在纸上,这样就可以将纸张撕成两半并丢弃一部分,而Kevins方式则会再次写出来在一张新纸上,你可以获得更多控制权,但速度稍慢。

编辑2: 由于我很无聊,我写了它是如何使用一个函数(有一些注释)来做的。请记住它的python 2而不是python 3我使用复制+粘贴不会为你工作。

def number_guess(tries, low, high):

    #Error if low is more than or the same as high
    if low >= high:
        raise ValueError('invalid range')

    #Build number list
    num_list = range(low, high + 1)
    print 'I have got {} tries'.format(tries)
    print 'And the number is between {} and {}'.format(low, high)

    for i in range(tries):
        guess = random.choice(num_list)
        print 'Is {} your number?'.format(guess)
        answer = input('Enter higher, lower or correct').lower()

        #Empty answer
        if not answer:
            continue

        #Correct answer
        if answer[0] in ('c', 'y'):
            print 'I guessed in {} tries'.format(i)
            return True

        #Number is higher
        if answer[0] == 'h':
            list_index = num_list.index(guess)
            num_list = num_list[list_index + 1:]

        #Number is lower
        elif answer[0] == 'l':
            list_index = num_list.index(guess)
            num_list = num_list[:list_index]

    #If it hits this point there are no tries left
    print 'I failed to guess'
    return False

tries = int(input('How many tries will you let me have?' ))
low = int(input('What is the lowest number I can guess?' ))
high = int(input('And what is the highest?' ))

success = number_guess(tries, low, high)