HackerRank Python (Basic) certification
Average Function
This is the shortest question in the Python (Basic) pool. It checks one thing: do you know how to write a function that takes any number of arguments.
What the question asks
You write a function called avg. HackerRank reads a line of space-separated integers, unpacks them into your function as separate arguments, and prints whatever you return with two decimal places. Your function has to return the arithmetic mean of all the numbers it receives. Sometimes it gets two numbers, sometimes ten.
Function to write
def avg(*nums):
...The editor only says “write your code here”. There is no ready-made signature, so you have to type the whole def line yourself. The name must be exactly avg, because the hidden code calls avg(*nums).
Solution
def avg(*nums):
return sum(nums) / len(nums)That is all you write. The input reading and the '%.2f' printing are already in HackerRank’s code below yours.
How it works
*numscollects every positional argument into a tuple. If the caller writesavg(1, 2, 3), thennumsis(1, 2, 3).sum(nums)adds them up andlen(nums)counts them.- In Python 3,
/always gives a float, soavg(2, 5)returns3.5and not3. - The stub formats the result with
'%.2f', so1.3333…is printed as1.33. You do not need to round anything.
Mistakes that fail the hidden tests
- Taking a list instead of
*nums.def avg(nums)breaks as soon as the stub callsavg(*nums)with more than one number: you get aTypeErrorabout too many positional arguments. - Using
//. Floor division turns 2.5 into 2, and the output becomes2.00instead of2.50. - Rounding yourself.
round(x, 2)before returning is harmless most of the time, but returning a formatted string likef"{x:.2f}"fails, because'%.2f' % "2.50"raises aTypeError. - Printing instead of returning. The stub writes your return value to the output file. If you
printand return nothing, the stub tries to formatNoneand crashes. - Wrong function name.
averageorAvggives aNameError.
Try it on sample data
Input line 1 2 3 4, which the stub passes as avg(1, 2, 3, 4):
print(avg(1, 2, 3, 4))
print('%.2f' % avg(1, 2, 3, 4))
print('%.2f' % avg(1, 1, 2))Output from my run:
2.5
2.50
1.33