Итерация по спискам в python - PullRequest
0 голосов
/ 22 февраля 2020

Я делаю программу, которая сначала принимает пользовательский ввод в форме тестовых ответов. Затем он запрашивает ключ ответа. Наконец, он должен сравнить каждый элемент в списке и определить оценку.

Вот пример запуска моей программы, в котором, как мы надеемся, она будет работать:

How many questions are there? >> 5
What is your answer for question #1 >> a
What is your answer for question #2 >> a
What is your answer for question #3 >> a
What is your answer for question #4 >> a
What is your answer for question #5 >> a


What is the correct answer for question #1 >> a
What is the correct answer for question #2 >> a
What is the correct answer for question #3 >> a
What is the correct answer for question #4 >> a
What is the correct answer for question #5 >> d

Total number correct : 4
Total number possible: 5
Grade = 4.0/5.0, 0.8%

Вот что на самом деле происходит :

How many questions are there? >> 5

What is your answer for question #1 >> a

What is your answer for question #2 >> a

What is your answer for question #3 >> a

What is your answer for question #4 >> a

What is your answer for question #5 >> a

Responses:

1. a
2. a
3. a
4. a
5. a

What is the correct answer for question #1 >> c

What is the correct answer for question #2 >> a

What is the correct answer for question #3 >> a

What is the correct answer for question #4 >> a

What is the correct answer for question #5 >> a

Responses:

1. c
2. a
3. a
4. a
5. a
a = c ?
a = a ?
a = a ?
a = a ?
a = a ?
a = c ?
a = a ?
a = a ?
a = a ?
a = a ?
a = c ?
a = a ?
a = a ?
a = a ?
a = a ?
a = c ?
a = a ?
a = a ?
a = a ?
a = a ?
a = c ?
a = a ?
a = a ?
a = a ?
a = a ?
20
Number of correct answers = 20 out of 5
Your score is: -3.0

Я не уверен, почему это происходит, возможно, это способ, которым я перебираю оба списка при оценке? Вот мой код:

class Grader:
    def grade(self):
        # get number of questions
        numOfQuestions = input("How many questions are there? >> ")

        # start gathering answers
        i = 1
        responses = []
        while i <= int(numOfQuestions):
            entry = input("\nWhat is your answer for question #" + str(i) + " >> ")
            responses += entry
            i += 1

        # display user responses
        print("\nResponses:\n")
        j = 1
        for r in responses:
            print(str(j) + ". " + r)
            j+=1

        # grade the responses
        # input answer key
        x = 1
        answers = []
        while x <= int(numOfQuestions):
            aentry = input("\nWhat is the correct answer for question #" + str(x) + " >> ")
            answers += aentry
            x += 1

        # display answer key
        print("\nResponses:\n")
        y = 1
        for z in answers:
            print(str(y) + ". " + z)
            y+=1

        # time to actually grade the exam
        numCorrect = 0
        for p in responses:
            for q in answers:
                print(p+" = " +q+" ?")
                if p == q:
                    numCorrect += 1

        # issue a grade
        print(str(numCorrect))
        print("Number of correct answers = " + str(numCorrect) + " out of " + str(numOfQuestions))
        grade = int(numOfQuestions) - int(numCorrect)
        grade = grade / int(numOfQuestions)
        print("Your score is: " + str(grade))





if __name__ == "__main__":
    a = Grader()
    a.grade()

Ответы [ 3 ]

1 голос
/ 22 февраля 2020

для сравнения вы можете использовать метод zip, с помощью которого мы можем l oop два списка одновременно, вот небольшое изменение для сравнения ответов на вопрос l oop

for p,q in zip(responses,answers):
    print(p+" = " +q+" ?")
    if p == q:
        numCorrect += 1
1 голос
/ 22 февраля 2020

Это здесь:

numCorrect = 0
for p in responses:
    for q in answers:
        print(p+" = " +q+" ?")
        if p == q:
            numCorrect += 1

Это сравнение каждый ответ на каждый ответ. Вы хотите сравнить каждый ответ только с соответствующим ответом. Самый простой способ - с помощью функции zip , например:

numCorrect = 0
for p, q in zip(responses, answers):
    print(p+" = " +q+" ?")
    if p == q:
        numCorrect += 1
0 голосов
/ 22 февраля 2020
class Grader:
    def grade(self):
        # get number of questions
        numOfQuestions = input("How many questions are there? >> ")

        # start gathering answers
        i = 1
        responses = []
        for i in range(0,int(numOfQuestions)):
            entry = input("\nWhat is your answer for question #" + str(i+1) + " >> ")
            responses.append(entry)


        # display user responses
        print("\nResponses:\n")

        for i in range(0,len(responses)):
            print(str(i) + ". " + responses[i])


        # grade the responses
        # input answer key
        answers = []
        for i in range (0,len(responses)):
            aentry = input("\nWhat is the correct answer for question #" + str(i+1) + " >> ")
            answers.append(aentry)


        # display answer key
        print("\nResponses:\n")

        for i in range(0, len(answers)):
            print(str(i) + ". " + answers[i])


        # time to actually grade the exam
        numCorrect = 0
        for i in range(0, len(answers)):
            print(str(i)," = ",answers[i]," ?")
            if responses[i] == answers[i]:
                numCorrect += 1

        # issue a grade
        print(str(numCorrect))
        print("Number of correct answers = " + str(numCorrect) + " out of " + str(numOfQuestions))
        grade = int(numOfQuestions) - int(numCorrect)
        if grade==int(0.0):
             print("Scored 100%")
        else:
             grade = int(numCorrect)/int(numOfQuestions)
             print("Your score is: ",grade)





if __name__ == "__main__":
    a = Grader()
    a.grade()
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...