I was on Hacker Rank for the first time and there was a question that required to get the inputs from STDIN and use
collections.namedtuple(). It was my first time working with getting inputs from STDIN so the way I acquired the inputs and used them to calculate the data might not be efficient.
The question was to calculate the average mark of the students and was given a multiple line string input with specific data about the student (like: NAME, CLASS, ID) in which one of them is MARKS (I have added an image of a sample STDIN input data below to explain better). But the layout of the input data could change so the code must be able to figure out where the MARKS are in the data and also get the number of students in order to calculate the average of their marks.
I came up with a quick way to solve this but was wondering how to appropriately and efficiently acquire the input data and perform the calculation.
Briefly, what is a better (pythony, efficient, shorter) way to write my code?
# Enter your code here. Read input from STDIN. Print output to STDOUT from collections import namedtuple import sys data = [line.rstrip().split() for line in sys.stdin.readlines()] sOMCache = ; n = 0 dataLength = len(data) if 'MARKS' in data : marksIndex = data.index('MARKS') for i in range(dataLength) : if n > 1 : sOMCache.append(data[n][marksIndex]) n += 1 sOM = sum([int(x) for x in sOMCache]) Point = namedtuple('Point','x,y') pt1 = Point(int(sOM), int((data))) dot_product = ( pt1.x / pt1.y ) print (dot_product)
5 ID MARKS NAME CLASS 1 97 Raymond 7 2 50 Steven 4 3 91 Adrian 9 4 72 Stewart 5 5 80 Peter 6
5 MARKS CLASS NAME ID 92 2 Calum 1 82 5 Scott 2 94 2 Jason 3 55 8 Glenn 4 82 2 Fergus 5