I am trying to create a program that that runs ten times that simulates someone randomly selecting a number 0-10 until they land on they guess the correct number 9. They must make sure to keep track of numbers that they already guessed so they don't guess them again. I need the size of the list to hold the number of guesses for each of the ten times the game was ran needed to reach 9.
The problem is i've ran into an infinite loop and can't get this to work. Does anyone have any advice? Thanks.
list1= []
for x in range(10):
guess= None
while guess != 9:
while guess in list1:
guess= rd.randint(0,10)
list1.append(guess)
size= len(list1)
print(size)
CodePudding user response:
The problem in your code is:
while guess in list1:
Its this while loop. For the first iteration(when x=0),we know that guess!=9, so it'll encounter this next while loop: while guess in list1
, now since list1 is empty as you have initialised at the top, it does not ever go into the loop and thus
while guess != 9:
goes into an infinite loop. I've modified your code a little bit to get the solution:
import random
for i in range(10):
lst = []
guess = 0
while guess!=9:
guess = random.randint(0,10)
if guess not in lst:
lst.append(guess)
print(len(lst))
CodePudding user response:
For a shorter code, you can simply use the random.shuffle
method, like this:
import random
for i in range(10):
cards = list(range(11)) # cards are in range [0:10]
random.shuffle(cards)
idx = cards.index(9) # index of 9 number
lst = cards[:idx 1] # take only 9-number and before
print(len(lst))
This code avoid also while
loop and is more determinist.