pbarBobo
pbarBobo

Reputation: 11

For loop to match items in 2 different lists

I could use a little advice. I am writing a simple version of Mastermind. The computer will choose a random number, which will choose a colour. These colours will be stored in a list (computerColours). The user will try to guess the correct colours in the correct positions. This will be stored in another list (userGuess).

I want to use a For loop to iterate through the colours in the 2 lists. I want to use an if statement to check if a colour is in both lists and see if there is a match. I want to return a Y if the guessed colour is in the same position as the computers list. I want to return a O if the guessed colour is in the computers list but not in the correct position.

I am struggling to get the following code to work:

for i in range(4):

        if userGuess[i] == computerColours[i]:
            print("Y")

           
        elif userGuess[i] != computerColours[i]:
            print("O")

Even if a guessed colour is not in the computer lists, it is still returning a O.

How can I include a check which will only return colours that are in both lists.

Thanks in advance

Upvotes: 0

Views: 54

Answers (3)

Mike67
Mike67

Reputation: 11342

Using list comprehension with zip seems to work.

computerColours = ['R','G','B','O']
userGuess       = ['R','P','B','O']

match = ' '.join(['Y' if i==j else 'O' for i,j in zip(computerColours, userGuess)])

print(match)  # Y O Y Y

Upvotes: 0

wasif
wasif

Reputation: 15498

To check if item is in list, use in:

for i in range(4):
  if userGuess[i] in computerColours:
    print("Y")
  else:
    print("O")

Upvotes: 0

Oliver Hnat
Oliver Hnat

Reputation: 793

I don't get the for loop, you could just do this

        if userGuess in computerColours:
            print("Y")

           
        elif userGuess not in computerColours:
            print("O")

Upvotes: 0

Related Questions