简体   繁体   中英

remove numbers from a list less than variable

I'm still early into learning to code, so sorry if the code is wonky... I'm making a number guessing game that guesses based on a first guess from two numbers the user gives and then puts those numbers into a list ascending. then my issue, i want to remove numbers lower/higher from my first guess then just do random.choice(list) code to follow....

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), "?")

I'm not comfortable with functions just yet which is why it's so much. once I get this perfectly ill change it to calling functions for the whole thing. -hopefully-

Change numbers.remove('''nums >= firstGuess''') to numbers.remove(firstGuess) You also need to take into account the numbers that are greater than your first guess, so you have to delete the ones before it. numbers = ([x for x in numbers if x > firstGuess]) should do the trick.

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)

This should get you started.

First off, while numberRangeLow < numberRangeHigh+1: do stuff is basically the same as range .
For the same result, you can use numbers = range(numberRangeLow, numberRangeHigh + 1) , which will build the list for you.

You also don't need to warn about it being case sensitive, if you use str.lower() it'll automatically put it into lower case. For example, you could do if answer.lower() == "higher" .

To remove numbers, you can do list slicing . For example, if you have a = [1, 2, 3, 4] , and it's lower than 3, you can get the index of 3 by using a.index(3) , which in this case, will give 2.
By then cutting off anything higher than this index with a[2:] , you have removed any higher numbers than 3.

Here's a quick update to your code doing the bits I mentioned.

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]

I rearranged the last part of the code so you didn't have 2 copies of the random choice. Also for the record, it's seen as better practice to name_variables_like_this and notLikeThis .

Edit: Kevins way is slightly different from mine, a simple comparison would be assuming you have written the numbers down on paper, this way would rip the paper in half and discard one part, whereas Kevins way would be writing it out again on a fresh sheet of paper, so you get more control, but it's a bit slower.

Edit 2: Since I'm bored, I wrote it how I'd do it with a function (with some comments). Bear in mind it's python 2 not python 3 I'm using so copy + paste won't work for you.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM