Python Writing A Program To Read and Find The Number Of Matching Letters In 2 Files and Return This Number

49 Views Asked by At

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()
1

There are 1 best solutions below

0
On

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()