简体   繁体   中英

Check if an element in one list has the same index as another element in another list

I am making the mastermind game on python with numbers. I have a problem with checking the elements if they are in an incorrect place.

So basically, if the code generated by the computer has no duplicates but the user used some in their input like (COMP: 1 2 3 4 & USER: 1 2 2 3). I can't check the positions of only one '2' and not both of them. Please help.

Code:

def incorrect_place():
        incorrect_place = 0

        if len(set(user_code)) != 4: #There are duplicates in the user's input
            for index, num in enumerate(set(user_code)):
                #I don't know how to check it now
                incorrect_place += 1

       return incorrect_place

I would like it if someone also finds a solution where the computer has chosen a duplicate and so has the user like (COMP: 1, 2, 2, 3 & USER: 2, 3, 4, 4)

Based on a little bit of research into what Mastermind is and the fact that the function in your OP returns an integer, my guess is that you want to compare a computer-generated list to a user-generated list of the same size and see how many positions have different values.

Example:

Computer: 1 2 3 4
User:     1 2 2 3
          S S D D   # S=Same, D=Different

So the answer above would be 2.

I propose the following:

def incorrect_places(comp_list, user_list):
    return sum(1 if a != b else 0 for a, b in zip(comp_list, user_list))

How it works:

  • zip(comp_list, user_list) gives us a list of 2-tuples, pairing the corresponding values in each list by the position in which they occur. For the above example, we'd get: [(1, 1), (2, 2), (3, 2), (4, 3)]
  • 1 if a != b else 0 for a, b in that_list -- returns a 1 if each number in the pair is the same, otherwise a 0. Thus, we get [0, 0, 1, 1]

Finally we sum it all to get our answer. Hope this helps.

Edit: Commenters have pointed out that this is the same as doing sum(a != b for a, b in zip(comp_list, user_list)) . I prefer the longer and more readable version, but they work the same way. This difference is purely stylistic. Choose whichever version you like.

I understood your question after reading Two-Bit Alchemist's answer. Here's my try:

def list_differences(list_a, list_b):
    # Subtract list_b from list_a, element by element. The subtraction 
    # will result in non-zero values for elements that were different.
    return [bool(list_a[i]-list_b[i]) for i in range(len(list_a))].count(True)

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