Home > front end >  Calculating the avg point of students from a txt file and return a dict
Calculating the avg point of students from a txt file and return a dict

Time:09-09

I'm quite new to Python and I have been working on this problem for a week, still can't figure this out, pls help.

The txt input file is like this (the first number in each line is the Student ID; Math, Phsc, Chem and Bio each has 4 scores, the rest has 5, separated by ';'):

StudentID, Math, Physics, Chemistry, Biology, Literature, Language, History, Geography

1; 5,7,7,8;5,5,6,6;8,6,7,7;4,8,5,7;7,7,6,7,9;7,5,8,6,7;7,8,8,5,9;5,8,6,8,7

2; 8,6,8,6;5,5,8,4;4,9,9,7;4,9,3,4;6,7,7,7,4;8,9,6,7,5;5,7,7,9,6;6,6,4,4,7

3; 5,8,9,8;7,8,8,7;6,6,7,6;5,7,9,7;6,3,5,8,8;5,6,6,6,8;7,7,6,6,7;8,5,3,6,4

4; 7,9,9,8;7,9,7,6;10,7,6,7;7,9,8,7;6,8,8,5,7;8,6,6,4,8;7,5,8,6,7;7,6,8,6,8

5; 9,7,4,6;4,6,5,5;7,5,6,7;6,9,7,6;7,9,7,6,6;6,7,7,8,8;7,9,6,8,6;8,6,8,8,5

6; 6,7,7,7;4,6,9,7;5,5,7,7;7,6,5,7;7,9,7,8,7;8,7,7,8,9;9,9,8,8,9;8,7,9,7,5

Math, Phsc, Chem and Bio have 4 weights for each score: 5%, 10%, 15%, 70%, which means, for example, the avg point of Math of Student 1 = 5x5% 7x10% 7x15% 8x70%

Litr, Lang, Hist and Geo has 5 weights: 5%, 10%, 10%, 15%, 60%

Requirment: Calculate the avg point of each student and output to a dict like this:

{‘Student 1’: {‘Math’: 9.00; ‘Physics’: 8.55, …}, ‘Student 2’: {…‘History’: 9.00; ‘Geography’: 8.55}}

Thank you.

CodePudding user response:

Considering that the script.py and your text file es student.txt are at the same path (directory):

final_dict = {}
with open("student.txt", "r") as f:
    for idx, l in enumerate(f.readlines()):
        if l != "\n":
            if idx == 0:
                l = l.replace("\n", "")
                header = l.split(", ")[1:]
            else:
                final_dict.update({f"Student {l[0]}": {}})
                marks = l.split("; ")[1].replace("\n", "").split(";")
                for i, mark in enumerate(marks):
                    current_subject_int_marks = tuple(map(int, mark.split(",")))
                    len_marks = len(current_subject_int_marks)
                    if len_marks < 5:
                        avr = (
                            current_subject_int_marks[0] * 0.05
                              current_subject_int_marks[1] * 0.10
                              current_subject_int_marks[2] * 0.15
                              current_subject_int_marks[3] * 0.70
                        )
                    else:
                        avr = (
                            current_subject_int_marks[0] * 0.05
                              current_subject_int_marks[1] * 0.10
                              current_subject_int_marks[2] * 0.10
                              current_subject_int_marks[3] * 0.15
                              current_subject_int_marks[4] * 0.60
                        )
                    final_dict[f"Student {l[0]}"].update({header[i]: avr})

print(final_dict)
  • Related