patternpythonMinor
Storing and retrieving student scores in three subjects
Viewed 0 times
threestudentsubjectsscoresandretrievingstoring
Problem
This is written to find percentages of three subjects. Original HackerRank practice problem is here.
Input Format
The first line contains the integer N, the number of students. The next N lines contains the name and marks obtained by that student separated by a space. The final line contains the name of a particular student previously listed.
Output Format
Print one line: The average of the marks obtained by the particular student correct to 2 decimal places.
This code is working but I need better way of writing this code.
Input Format
The first line contains the integer N, the number of students. The next N lines contains the name and marks obtained by that student separated by a space. The final line contains the name of a particular student previously listed.
Output Format
Print one line: The average of the marks obtained by the particular student correct to 2 decimal places.
This code is working but I need better way of writing this code.
a = input()
a = int(a)
dict = {}
f = []
n = {}
for i in range(a):
f = input().split()
name = f[0]
n['phy'] = float(f[1])
n['che'] = float(f[2])
n['math'] = float(f[3])
f = []
dict[name] = n
n ={}
nam = input();
per = (dict[nam]['phy']+dict[nam]['che']+dict[nam]['math'])/3
print("%.2f"%per)Solution
PEP 8, the official Python style guide, specifies four spaces per level of indentation. Since whitespace is significant in Python, that is a pretty strong convention.
The challenge states that the first line contains N, the number of students. So, don't call that value
The variable
Clearing
For this problem, there is no need to store the scores for each subject separately. You can just store the average right away.
The challenge states that the first line contains N, the number of students. So, don't call that value
a in the code, and don't use the variable n to mean something else. It's confusing.The variable
i is never used. It is customary to use _ as the name of a "throwaway" variable whose value does not matter.Clearing
f and n at the end of the loop is cumbersome and unnecessary. Avoid cryptic variable names like f and n whose meanings are not obvious. Even names like nam and per are unnecessarily unfriendly. (Learn from Ken Thompson's biggest regret.)For this problem, there is no need to store the scores for each subject separately. You can just store the average right away.
scores = {}
n = int(input())
for _ in range(n):
line = input().split()
name = line.pop(0)
scores[name] = sum(float(score) for score in line) / len(line)
print("%.2f" % scores[input()])Code Snippets
scores = {}
n = int(input())
for _ in range(n):
line = input().split()
name = line.pop(0)
scores[name] = sum(float(score) for score in line) / len(line)
print("%.2f" % scores[input()])Context
StackExchange Code Review Q#149166, answer score: 6
Revisions (0)
No revisions yet.