Combining pythons min
function with the key
option, this is a one-liner:
numbers = [1, 2, 3, 4, 5]
closest_to_avg = min(numbers, key=lambda x: abs(x - sum(numbers)/len(numbers)))
print(closest_to_avg)
# 3
Explanation, via break-down to more lines:
avg_of_numbers = sum(numbers) / len(numbers)
print(avg_of_numbers)
# 3
So the average can be calculated without any (explicit) loops.
Now what you need is to just calculate the absolute difference between each of numbers
and the average:
abs_diffs_from_avg = [abs(x - avg_of_numbers) for x in numbers]
The number in numbers
minimizing this diff is the number you want, and you can see this by looking at each number and its corresponding diff:
print([(x, abs(x - avg_of_numbers)) for x in numbers])
# contains the pair (3, 0.0), which is indeed the minimum in this case)
So you just pass this diff as the key
to the min
function...
(Regarding usage of the key
input, this is defined as "a function to customize the sort order", and is used in sort
, max
, and other python functions. There are many explanations of this functionality, but for min
it basically means "use this function to define the ordering of the list in ascending order, and then just take the first element".)
EDIT:
As recomended in the comment, the average should be calculated outside the min, so as to avoid recalculating. So now it's a two-liner ;-)
numbers = [1, 2, 3, 4, 5]
avg_of_numbers = sum(numbers) / len(numbers)
closest_to_avg = min(numbers, key=lambda x: abs(x - avg_of_numbers))
print(closest_to_avg)
# 3