the problems state that we using namedtuple storing students records and finding the total average of all students marks for this taking total number of record and each column names one by one and then taking values for each column to till records and calculate .
Average = sum of total marks / total number of students
Here is not optimized solution because takes is to finish it under the 4 lines
and we doing operations twice times but it starting point.
one loop collecting each columns values and other just unpacking and increment variable of total_marks and at the end we just divide it with length of our all students named tuples from list.Althoguh time complexity still considered as Big (O)n.
Problem:https://www.hackerrank.com/challenges/py-collections-namedtuple/problem?isFullScreen=true
CODE:
# Naive
Code Solutions:
Input Parsing:
n, column_names = int(input()), input().split():First, the code reads an integer
n, which represents the number of students.Then, it reads the next line which contains column names (like
NAME,CLASS,MARKS), and splits them into a list of stringscolumn_names.
NamedTuple Creation:
StudentRecord = namedtuple('StudentRecord', column_names):This line defines a
namedtupleclassStudentRecordwith fields specified bycolumn_names. Anamedtuplecreates lightweight objects where each field can be accessed by name, likestudent.NAME,student.CLASS, etc.
List Comprehension for Student Records:
students = [StudentRecord(*input().split()) for _ in range(n)]:This is a list comprehension that loops
ntimes, taking input for each student and splitting their data (e.g.,John 10 90) into separate values.It then unpacks the values into the
StudentRecordnamed tuple, which gives us a list ofStudentRecordobjects where each object holds the student's data.
Average Calculation:
print(sum(int(student.MARKS) for student in students) / n):This line calculates the sum of the
MARKSfor all students. It uses a generator expression to extract theMARKSfield, converts it to an integer, and sums them up.Finally, it divides the total marks by
nto compute the average and prints the result.
Time Complexity:
The time complexity is O(n) because the program loops over the student records once to collect the data and once more to compute the sum of the marks.
