python: compare list containing multiple lists with a different list only

Asked

Viewed 1,318 times

7

I’m solving an issue where I have to do a program that corrects tests. The program receives a feedback and answers from "n" students and compares with the feedback provided. The answers of all students are put on a single list. My problem is, how to compare the list of answers to the feedback and print an individual note for each student.

Ex:

gabarito = ['a','b','c','d','e']

resposta_alunos = [['a', 'b', 'c', 'd','d'],['a', 'a', 'c', 'd','d'],...]

2 answers

8


I tried to do something as simple as possible. See:

# -*- coding: utf-8 -*-
from __future__ import unicode_literals
respostas = [
    ['a', 'b', 'c', 'd', 'e'],
    ['d', 'c', 'c', 'a', 'd'],
    ['d', 'c', 'd', 'b', 'a'],
    ['d', 'c', 'c', 'b', 'e']
];

gabarito = ['d', 'c', 'c', 'b', 'e']

for r_num, resposta in enumerate(respostas):

    total = 0;

    for g_num, valor in enumerate(gabarito):

        # Se a posição do valor do gabarito é o mesmo da resposta e os valores iguais

        if resposta[g_num] == valor:
            #Suponhamos que cada acerto vale 2 pontos
            total = total + 2; 

    print "O aluno %s tirou %d pontos" % (r_num, total)

When running the above code, the result should be:

O aluno 0 tirou 4 pontos
O aluno 1 tirou 6 pontos
O aluno 2 tirou 6 pontos
O aluno 3 tirou 10 pontos

Supposing you have some notion of python, realize that the passage resposta[g_num] I capture through the feedback index the value of one of the answers. This is because, in a feedback, there is a number of the question (which would be the index in our case), and therefore must hit, at the same time, the question number and answer value.

That’s what I got. I don’t know if in this case the use of a list would be ideal.

1

Another possibility is to use the numpy.

Using the @Wallace-maxters response data, we can get the amount of hits as follows.

import numpy as np

respostas = [
    ['a', 'b', 'c', 'd', 'e'],
    ['d', 'c', 'c', 'a', 'd'],
    ['d', 'c', 'd', 'b', 'a'],
    ['d', 'c', 'c', 'b', 'e']
];

gabarito = ['d', 'c', 'c', 'b', 'e']

# Transforma em um array
respostas_arr = np.array(respostas)
gabarito_arr = np.array(gabarito)

# Verifica os acertos
verificacao = respostas_arr == gabarito_arr
#[[False False  True False  True]
# [ True  True  True False False]
# [ True  True False  True False]
# [ True  True  True  True  True]]

# Soma os acertos
acertos = verificacao.sum(1)
#[2 3 3 5]

# Imprime os resultados
for n, i in enumerate(acertos):
    print('O aluno {} acertou {} questões'.format(n+1, i))
#O aluno 1 acertou 2 questões
#O aluno 2 acertou 3 questões
#O aluno 3 acertou 3 questões
#O aluno 4 acertou 5 questões

Compacting Everything in a Row:

acertos = (np.array(respostas) == np.array(gabarito)).sum(1)
#[2, 3, 3, 5]

Browser other questions tagged

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