How to compare elements of the same index in a list

Asked

Viewed 2,163 times

4

I have the following problem to solve:

Consider that Mariazinha has performed a multiple choice approval. We now want to determine the number of hits Mariazinha. To this end, the template and responses are provided in two consecutive lines, both in the form of a String of the same length. The entry can be given as below, the result being an integer number corresponding to the number of hits (5, in this case):

abcbdab
aecbaab

My idea to solve the problem was to create two separate lists, one containing the answers, and the other, the feedback. However, I do not know how I can compare the first element of a list with the first element of the other, and only this; that is, after the comparison, the program moves to the next element. I tried to execute the following code:

def numeros_de_acertos(escolhas,gabarito):
    c = 0
    lista_escolhas = list(escolhas)
    lista_gabarito = list(gabarito)
    
    
    for x in lista_escolhas:
        for y in lista_gabarito:
            if x == y:
                c += 1
    return c

However, in the repeating structure, he compares the first element with all elements of the second list, adding more hits to the counter than it should.

Can someone help me solve this problem?

1 answer

5


You don’t need to convert the strings for lists. In Python, the strings are also eternal. The simplest way for you to make this comparison is to create a zip between the two strings and compare values:

escolhas = 'abcbdab'
gabaritos = 'aecbaab'

acertos = 0

for escolha, gabarito in zip(escolhas, gabaritos):
    if escolha == gabarito:
        acertos += 1

print(f'Acertou {acertos} questões')

See working on Repl.it | Ideone

However, if we remember that the boolean type in Python is defined as a subtype of int, where True is worth 1 and False is worth 0, we can only do the same check, but adding directly the result of the condition:

for escolha, gabarito in zip(escolhas, gabaritos):
    acertos += (escolha == gabarito)

Or using in reduced form, making use of the function sum:

acertos = sum(escolha == gabarito for escolha, gabarito in zip(escolhas, gabaritos))
  • Thank you so much! : ) I’m still beginner in python and I didn’t know the ZIP function. I did another search and I got it. Thanks!

  • I didn’t know that True is the same as 1. Very good. + 1

Browser other questions tagged

You are not signed in. Login or sign up in order to post.