Reputation: 25
Program reads a set of answers from python. l_answers would be the correct ones. l_rscore would be the answers read from the file and now indexed to a list.
I need to know how would I go on if I want to compare each other (list[0] || list2[0]) and check the amount of correct answers and incorrect ones.
Current approach is not working and gives no traceback. It just keeps 'computing', never ending.
def main():
l_answers = [['B', 'D', 'A', 'A', 'C'],
['A', 'B', 'A', 'C', 'D'],
['B', 'C', 'D', 'A', 'D'],
['C', 'C', 'B', 'D', 'A']]
l_rscore = read_file()
result = get_result(l_answers, l_rscore)
print result
def read_file():
rows = 4
colums = 5
l_results = []
input_file = open('answers.txt', 'r')
for r in range(rows):
for c in range(colums):
for line in input_file:
l_results.append(line.strip())
return l_results
def get_result(l, l_2):
correct = 0
index = 0
while index < len(l):
if l_2[index] == l[index]:
correct += 1
index += 1
return correct
main()
Upvotes: 0
Views: 80
Reputation: 31339
You have an infinite loop in get_result
where you have a condition before increasing the index
which doesn't always hold.
Generally, if you have two lists, one of which is the answers and the other is the suggestions (with the same order) - you can use zip to handle them together:
def compare_answers(suggestions, answers):
# pair what was answered with what's true
pairs = zip(suggestions, answers)
# summarize scores - 1 for each correct answer
return sum(i == j for i, j in pairs)
Note: When adding True
to a number, it's treated as 1 (False
is 0). So sum
gives us the number (sum defaults to start from 0).
Upvotes: 2
Reputation: 16711
First of all, you need to read the file like so input_file = open('answers.txt', 'r').read()
and then you must parse this into a nested list. Secondly, your loop at the bottom should be:
while index < len(l):
if l_2[index] == l[index]:
correct += 1
index += 1
EDIT: If your file is written as a list of lists, you can construct a list easily like so, evaluating the contained string as a list.
input_file = eval(open('answers.txt', 'r').read())
Upvotes: 0
Reputation: 2826
You could flatten both of your lists and compare them via a list comprehension.
def get_results(l, l2):
lflat = [i for sublist in l for i in sublist]
l2flat = [i for sublist in l2 for i in sublist]
return sum(i[0] == i[1] for i in zip(lflat, l2flat))
Upvotes: 2
Reputation: 4445
Your infinite loop is right here:
index = 0
while index < len(l):
if l_2[index] == l[index]:
correct += 1
index += 1
If the first answers aren't equal to each other, index never gets incremented, and the while loop keeps iterating, stuck on the first answers.
Upvotes: 1