Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
comparing two lists
#11
You don't need index_position. The index loop variable gives you exactly the same values. That's what the for loop and the range do for you.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#12
Okay, this is the finished product.
def main():
    CORRECT_ANSWERS = ["A" , "C" , "A" , "A" , "D" ,
                       "B" , "C" , "A" , "C" , "B" ,
                       "A" , "D" , "C" , "A" , "D" ,
                       "C" , "B" , "B" , "D" , "A"]


    student_answers = []

    student_file = open("test.txt" , "r")


    for line in student_file:
        student_answers.append(line.rstrip('\n'))


    student_file.close()

    incorrect_num = []
    correct_answers = 0

    for index in range(len(CORRECT_ANSWERS)):

        if CORRECT_ANSWERS[index] == student_answers[index]:
            correct_answers += 1
        else:
            incorrect_num.append(index + 1)

    if correct_answers > 14:
        print("The student passed.")
    else:
        print("The student failed.")

    print("The student got %d answer(s) correct and %d answer(s) incorrect." % (correct_answers, (20 - correct_answers)))
    print("This is a list of the question number(s) answered incorrectly." , incorrect_num)


main()
I still have to comment the whole thing. Thank you again for the help.
Reply
#13
Some observations:

- if feasible you can outsmart your teacher by defining of your own zip function and taking advantage code snippet provided by ichabod801 earlier in this thread. Python documentation about built-in function zip() contains code how zip functionality is implemented.

- I suggest to open files differently, using with statement (no need to close file + some other benefits):

>>> with open("test.txt" , "r") as f:
...     student_answers = []
...     for line in f:
...         student_answers.append(line.strip('\n')) 
If you have learnt list comprehension then you could have:

>>> with open('test.txt', 'r') as f:
...     student_answers = [line.strip('\n') for line in f]
Or even:

>>> student_answers = [line.strip('\n') for line in open('test.txt', 'r')]
- if you are using main() then you could move reading the student answers into separate function as well as returning number of correct answers and list of incorrect answers. It can improve readability of your code.

- in printing I recommend using f-strings or .format method. They are 'modern' and subjectively more readable

- You have hardcoded 20 to determine number of incorrect answers (row 34). You could use len(CORRECT_ANSWERS) - correct_answers. This way your message will be correct if number of questions changes. Same principle can probably applied to code on row 29 where it seems that 75% is required to pass.

- maybe you should use different name for number of student correct answers; currently there is possibility to mix up 'CORRECT_ANSWERS' and 'correct_answers'

- row 35 you will print out list with square brackets. You could print out values without square brackets and separated with commas: print('Your message', ', '.join([str(x) for x in incorrect_num])
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#14
So I spoke with my professor today and I see the disconnect now. I am in a Programming Logic and Object Oriented Design class and not a Python class. Python is the teaching medium that they are using to teach the logic and design. Their goal is to make us understand the logic not to teach us Python. It means I will be doing double programs, one that fits her requirements, and one that will unlock Python's abilities and help me further understand the language itself. I have saved all of the suggestions to my notes and thank you all for the help. I will be working on these same two programs unrestricted for a personal challenge.
Reply
#15
(Jan-22-2019, 06:56 PM)Siylo Wrote: I am in a Programming Logic and Object Oriented Design class and not a Python class.

That makes much more sense.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#16
Okay, so I was playing around and I have an error I don't know how to fix.
def main():

    # Constant of correct test answers.
    CORRECT_ANSWERS = ["A" , "C" , "A" , "A" , "D" ,
                       "B" , "C" , "A" , "C" , "B" ,
                       "A" , "D" , "C" , "A" , "D" ,
                       "C" , "B" , "B" , "D" , "A"]

    # filling a list with every line, stripped of the \n, from the opened file
    student_answers = [line.strip('\n') for line in open('test.txt', 'r')]

    student_correct = 0
    incorrect_num = [(index + 1) if CORRECT_ANSWERS[index] != student_answers[index] else
                     (student_correct +1) for index in CORRECT_ANSWERS]

    print(incorrect_num)


main()
The error is
Error:
Traceback (most recent call last):File "", line 15, in <listcomp> (student_answers +1) for index in CORRECT_ANSWERS] TypeError: list indices must be integers or slices, not str
I fixed the student_answers +1 to student_correct +1. I noticed it after but it doesn't change the error.
Reply
#17
Let's rewrite it a bit, because I don't think index is what you think it is.
>>> CORRECT_ANSWERS = ["A" , "C" , "A" , "A" , "D" ,
...                        "B" , "C" , "A" , "C" , "B" ,
...                        "A" , "D" , "C" , "A" , "D" ,
...                        "C" , "B" , "B" , "D" , "A"]
>>> for index in CORRECT_ANSWERS:
...   print(index)
...
A
C
A
A
D
B
C
A
C
B
A
D
C
A
D
C
B
B
D
A
If you actually do want the index, and not the elements of the list, then enumerate() is your hero.
>>> for index, item in enumerate(CORRECT_ANSWERS):
...   print(f"{index} => {item}")
...
0 => A
1 => C
2 => A
3 => A
4 => D
5 => B
6 => C
7 => A
8 => C
9 => B
10 => A
11 => D
12 => C
13 => A
14 => D
15 => C
16 => B
17 => B
18 => D
19 => A
If you look back at your previous code, you were looping over range(len(CORRECT_ANSWERS)), but now you're looping over the list directly, which doesn't give indices.
Reply
#18
I do want the indexes, at the end I'm trying to print out a list of the incorrectly answered questions so question 1 == index 0.
def main():
    # Constant of correct test answers.
    CORRECT_ANSWERS = ["A", "C", "A", "A", "D",
                       "B", "C", "A", "C", "B",
                       "A", "D", "C", "A", "D",
                       "C", "B", "B", "D", "A"]

    # filling a list with every line, stripped of the \n, from the opened file
    student_answers = [line.strip('\n') for line in open('test.txt', 'r')]

    student_correct = 0
    incorrect_num = [(index + 1) if CORRECT_ANSWERS[index] != student_answers[index] else
                     (student_correct + 1) for index in range(len(CORRECT_ANSWERS))]

    print(incorrect_num)
    print(student_correct)

main()
now my output is
Output:
[1, 1, 1, 1, 5, 1, 7, 1, 1, 10, 1, 1, 1, 1, 15, 1, 1, 1, 1, 20] 0
The list of incorrectly answered questions should be [1,5,7,10,15,20] and 14 should be the student_correct value.
Reply
#19
I copied in the student_answers list again to make it easier.
def main():
    # Constant of correct test answers.
    CORRECT_ANSWERS = ["A", "C", "A", "A", "D",
                       "B", "C", "A", "C", "B",
                       "A", "D", "C", "A", "D",
                       "C", "B", "B", "D", "A"]

    # filling a list with every line, stripped of the \n, from the opened file
    #student_answers = [line.strip('\n') for line in open('test.txt', 'r')]
    student_answers = ["B", "C", "A", "A", "A",
                       "B", "A", "A", "C", "C",
                       "A", "D", "C", "A", "A",
                       "C", "B", "B", "D", "D"]

    student_correct = [(index + 1) for index in range(len(CORRECT_ANSWERS))
                       if CORRECT_ANSWERS[index] == student_answers[index]]

    incorrect_num = [(index + 1) for index in range(len(CORRECT_ANSWERS))
                        if CORRECT_ANSWERS[index] != student_answers[index]]

    print(incorrect_num)
    print(len(student_correct))
    print("Passed" if (len(student_correct) / len(student_answers)) >= .75
          else print("Failed"))
main()
I don't know where the None is coming from in the output though.

Output:
[1, 5, 7, 10, 15, 20] 14 Failed None
Reply
#20
None is coming from else print("Failed"). The print function returns None. So that print displays "Failed" and returns None to the print is within, which displays 'None'.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Comparing 2 lists BerryK 4 4,519 Apr-15-2017, 09:46 AM
Last Post: volcano63

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020