tags:
- code
topic: Sum
difficulty: Easy
link: https://www.codewars.com/kata/5601409514fc93442500010b/solutions/python
date: 2023-10-20
Problem
Write a function that accepts two arguments: a list of scores, and your score. Return True if your score is higher than the mean of the total class.
What the creator of this problem failed to consider was enforcing the requirement of adding your own score to the list of total scores. This is something that would affect the average, and hence, whether your score is higher than the mean.
The test cases provided conveniently work regardless of whether your own score is added.
better_than_average([2, 3], 5) # Returns True
better_than_average([100, 40, 34, 57, 29, 72, 57, 88], 75) # Returns True
better_than_average([41, 75, 72, 56, 80, 82, 81, 33], 50) # Returns False
def better_than_average(class_points, your_points):
total = sum(class_points + [your_points])
return total/len(class_points) <= your_points
return True if total[..] else False
. However, this is unnecessary due to the comparison operator (<=
) returning the status of the comparison anyways.def better_than_average(class_points, your_points):
average = (sum(class_points) + your_points) / (len(class_points) + 1)
return your_points > average
def better_than_average(*args):
return args[1] > sum(*args) / (len(args[0]) + 1.0)
*args
syntax to take into account both passed values, yet it can still distinguish between the class_points
/args[0]
and your_points
/args[1]
variables via indexing.
*args
means that you don't even need to combine class_points
and your_points
! You can just use sum
on the entire thing, which does account for the latter value.len(foo)
on the class_points
(since that was already passed as a list), with then adding one to account for the single your_points
value.