GamErik13
GamErik13

Reputation: 35

Having problems while comparing two lists

I would like to take the input of the user, giving me an ID. After getting the ID, I should check if the answers connected to the ID match the already given correct answers. If they do, I should print a "+", otherwise a " ". This is similar to my first question, but unfortunately I still do not really understand the problem, I got two different errors throughout my testing, one of them was the list is out of range one the other was string indices must be integers. My correct answers are in a list, consisting only of one element, I don't know if it's easier not having it in a list, but simply a string connected to a variable. correct_answer ="BCCCDBBBBCDAAA" or correct_answer = ["BCCCDBBBBCDAAA"]. The other list, answers consists of a long list, having sub-lists looking like this, ['AB123', 'BXCDBBACACADBC']. In my case I input "AB123" as my choice.

Commented in third part.

user_choice = input("Provide an ID")
print(correct_answer,"(a helyes megoldás)")
for line in answers:
    if user_choice == line[0]:
        for index in line[1]:
            if line[1][index] == correct_answer[index]:
                print("+", end="")
            else:
                print(" ", end="")

My expected output would be put the pluses below the correct answer, leaving spaces when it did not match.

But I am getting the error. It would mean a lot if someone could explain the problem when comparing the indexes and why is there a problem.

Upvotes: 1

Views: 42

Answers (2)

Angelo Mendes
Angelo Mendes

Reputation: 978

Using this for index in line[1]:, the index is an element existent in line[1], not an index value.

See about range, the code below can help you.

for index in range(0, len(line[1])):
     if line[1][index] == correct_answer[index]:
         print("+", end="")
     else:
         print(" ", end="")

Upvotes: 1

J_H
J_H

Reputation: 20450

These two lines don't make much sense:

        for index in line[1]:
            if line[1][index] == correct_answer[index]:

You named the variable index, but a more accurate name would be character.

Zip is probably the simplest and most pythonic way out of that trouble:

        for ans_ch, corr_ch in zip(line[1], correct_answer):
            if ans_ch == corr_ch:

Alternatively you might use for i in range(len(line[1])): and then index with i.

Upvotes: 1

Related Questions