Skip to content
Advertisement

Finding the “centered average” of a list

“Return the “centered” average of a list of integers, which we’ll say is the mean average of the values, except ignoring the largest and smallest values in the list. If there are multiple copies of the smallest value, ignore just one copy, and likewise for the largest value. Use integer division to produce the final average. You may assume that the list is length 3 or more.”

This is a problem I have from my homework assignment and I am stumped at how to find the the largest/smallest numbers and cut them out of the list. Here is what I have so far. and It works for 10/14 the scenarios that I have to pass.. I think it is just because it grabs the median

def centered_average(nums):
x = 0
for i in range(len(nums)):
    x = i + 0
y = x + 1
if y%2 == 0:
    return (nums[y/2] + nums[(y/2)+1]) / 2
else:
    return nums[y/2]

Advertisement

Answer

Sorting the array is certainly terser code, here’s an alternative with a manual loop

    max_value = nums[0]
    min_value = nums[0]
    sum = 0
    for x in nums:
        max_value = max(max_value, x)
        min_value = min(min_value, x)
        sum += x

    return (sum - max_value - min_value) / (len(nums) - 2)

This just adds everything in and removes the max and min at the end.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement