0

Here is the code I have so far I used 2 groups of letters in 2 files, I then used index() to find the number of letters matching then len() to return the total number When I run the code I am getting this, There are 19 correct answers

I was wondering why this may be, as I am expecting, There are 7 matches, it seems to be counting and returning every character in the text file

user.txt

A   C   B   A   A   D   B   B   C   A

answers.txt

A   C   A   A   A   B   B   B   C   D
fileObj1 = open("user.txt", 'r')
fileObj2 = open("answers.txt", 'r')

user = fileObj1.read()
answer = fileObj2.read()
results = len([user.index(i) for i in answer])
print("There are", results, "correct answers")

fileObj1.close()
fileObj2.close()
Will Beason
  • 3,417
  • 2
  • 28
  • 46
  • You are checking each character of the first file to all characters of the second file since you are looping in the answer variable. You have to move each through character in both the files at the same time. – noswear May 12 '21 at 06:17
  • @noswear so how would I implement this into my code, would you be able to show? I'm having a hard time understanding – njtmann May 12 '21 at 06:22
  • Welcome to Stack Overflow! What is the exact output you get when you run your code, and what is the exact output you would like? If you add those to your question, it will be much easier to help. – Will Beason May 12 '21 at 19:21
  • As I'm reading it this is to check the answers on a multiple choice test where one file is the correct response and one is the student's answers. Is that correct? Context helps see your end goal. – Lio Elbammalf May 13 '21 at 06:33

1 Answers1

0

Well, this may not be the optimized way but you can give it a go. However, I haven't tested it. Assuming both files have an equal number of responses.

fileObj1 = open("user.txt", 'r')
fileObj2 = open("answers.txt", 'r')

user = fileObj1.read()
answer = fileObj2.read()
results = 0

for i,j in zip(user,answer):
    if i==j:
        results = results + 1

print("There are", results, "correct answers")

fileObj1.close()
fileObj2.close()
noswear
  • 311
  • 1
  • 6
  • 27