Hanwool Codes RSS Tag Admin Write Guestbook
2023-03-08 03:14:27

Collections.namedtuple() | HackerRank

 

Collections.namedtuple() | HackerRank

You need to turn tuples into convenient containers using collections.namedtuple().

www.hackerrank.com

 

Goal

 

Dr. John Wesley has a spreadsheet containing a list of student's IDs, marks, class and name.
Your task is to help Dr. Wesley calculate the average marks of the students.

Print the average marks of the list corrected to 2 decimal places.

 

Solution

 

You use collections.namedtuple()  to solve this task.

 

This code takes input from the standard input (STDIN) in the following format:

  • The first line contains an integer n, which represents the number of students.
  • The second line contains space-separated strings representing the columns of the table.
  • The following n lines contain space-separated values representing the data for each student.

The first line of code reads the integer value n from the standard input and stores it in the variable n.

The second line reads the column names from the standard input 

and converts them into a list of strings using the split() method. 

The index() method is then used to find the index of the 'MARKS' column, which is stored in the variable colum.

The for loop iterates n times, and for each iteration, 

it reads the input data for a student, splits the input string into a list of values using the split() method, 

and adds the value in the 'MARKS' column to the variable average.

Finally, the average of the 'MARKS' column is calculated 

by dividing the sum of all the values in the 'MARKS' column by n.

The result is then printed to the standard output (STDOUT) using the format() method

with a precision of two decimal places.

 

# Collections.namedtuple()

# Enter your code here. Read input from STDIN. Print output to STDOUT
n = int(input())
colum = input().split().index('MARKS')
average = 0.0

for i in range(n):
    data = input().split()
    average += float(data[colum])


print('{:.2f}'.format(average / n))
Hanwool Codes. Designed by 코딩재개발.