HackerRank Problem: Finding the Percentage
Let me start by saying I am not a programmer or developer. I use Python, which is by far the easiest coding language to learn. It’s not the fastest or the most robust, but it is easy to read, easy to write, and works for what I use it for. I have used it as a makeshift calculator, a way to keep track of my hours at work throughout the week, and even as a dice roller for game nights. Today, I am going to go through one of the problems I came across on HackerRank and how it led me to solving a problem I didn’t know I had.
To start, HackerRank is a site dedicated to educating and testing developers in various fields and languages (here is a link to the specific problem I was working on). It is a great place to practice for any level of programmer. The problem I was working on takes in a certain number of inputs that contain the name of a student and their test scores. At the end, the name of one of the students is passed and the output of their average score is displayed. The output is displayed as a 2-decimal place number, like a price. Here is an example of what the code takes in as input and what it should return as output:
Sample Input
3
Krishna 67 68 69
Arjun 70 98 63
Malika 52 56 60
Malika
Sample Output
56.00And here is the Python code that was provided:
if __name__ == '__main__':
n = int(input())
student_marks = {}
for _ in range(n):
name, *line = input().split()
scores = list(map(float, line))
student_marks[name] = scores
query_name = input()My first goal was to create a variable that could keep track of the total from the student I was grabbing the scores from. I also wanted to use a for-loop that would run enough times to get all the scores. I like using this technique because the amount of scores could change from student to student. Lastly, to take the average, I would need to divide the total by how many entries there were. Here is how I accomplished this on my original aubmission:
total = 0
for i in range(len(student_marks[query_name])):
total += student_marks[query_name][i]
print(total/(i+1))This will not return the correct answer though, as this will only display one decimal point. I thought that the Python round() method would be what I needed to use. So here is what I tried:
print(round(total/(i+1),2))
>>56.0Unfortunately, Python’s round() method does not add trailing zeros to a number. In fact, round() will only return one trailing zero, no matter how many digits of precision you specify. You can test this by trying to enter in the following:
round(56.00, 2)
>>56.0The output will be the same as before. This is because round() only changes the specified digit if there is something to round.
round(56.007,2)
>>56.01So, I needed to use a method that I knew nothing about: the str.format method.
Get Viktor Dominguez’s stories in your inbox
Join Medium for free to get updates from this writer.
The str.format method works by taking in a replacement field (designated by “{}”) and providing the arguments to the format() method. If that sounds like a bunch of mumbo-jumbo, don’t worry. I still don’t understand all of the ways the format() method can be used, but here is a walkthrough using our problem.
print('{:.2f}'.format(total/(i+1)))
>>56.00Let’s start with the ‘{:.2f}’ part. As mentioned before, the “{}” designates a replacement field. So, in our case, we use “:”, known as the format specifier, which tells the formatter this is a non-default format. We specified that we wanted the value to be formatted as ‘.2f.’ This breaks down to “2 decimal place” float precision (or at least, that’s how I read it). If we had omitted the f character, we would get a different format (in this case, a scientific notation format). Or, had we replaced the f with an n character, we would get a standard number output (like an integer). You can find the official documentation for the str.format() method here.
So, there’s our answer. The str.format() method allowed us to overwrite the standard display of a float in order to show the additional trailing decimal places. We could use this to show any number of digits.
print('{:.3f}'.format(total/(i+1)))
>>56.000
print('{:.5f}'.format(total/(i+1)))
>>56.00000There are other formats that can be output with the str.format() method. This can be useful if we want to output a different format like a price or a time. Here is an introductory tutorial on W3School’s website that breaks down all of the formatting types.
Here is my final solution:
if __name__ == '__main__':
n = int(input())
student_marks = {}
for _ in range(n):
name, *line = input().split()
scores = list(map(float, line))
student_marks[name] = scores
query_name = input()
total = 0
for i in range(len(student_marks[query_name])):
total += student_marks[query_name][i]
print('{:.2f}'.format(total/(i+1)))Later, I condensed the code down by using sum() and len() instead of using the total and the for-loop.
if __name__ == '__main__':
n = int(input())
student_marks = {}
for _ in range(n):
name, *line = input().split()
scores = list(map(float, line))
student_marks[name] = scores
query_name = input()
print('{:.2f}'.format(sum(student_marks[query_name])/len(student_marks[query_name])))






