Task 1: Special Average
"Trim the Extremes: What’s the Real Average?"
This week's first task asks us to compute an average after excluding the minimum and maximum values from the given array. If removing those extremes leaves no remaining values, the result should be 0, which also covers the case where every element is identical.
The Strategy: Find the minimum and maximum values first. If they are equal, everything is the same and the answer is immediately 0. Otherwise, remove all occurrences of the minimum and maximum, then compute the average of what remains. If nothing remains after filtering, return 0.
Perl Implementation
sub special_average ($ints) {
($ints) = $LIST_CHECK->($ints);
return 0 unless @$ints;
my $min = min(@$ints);
my $max = max(@$ints);
return 0 if $min == $max;
my $min_count = grep { $_ == $min } @$ints;
my $max_count = grep { $_ == $max } @$ints;
my $remaining = @$ints - $min_count - $max_count;
return 0 if $remaining <= 0;
my $total = sum0(@$ints) - ( $min * $min_count ) - ( $max * $max_count );
return $total / $remaining;
}
Python Implementation
def special_average(ints: Sequence[float]) -> float:
"""
Return the average after removing all occurrences of the minimum and maximum.
"""
if not ints:
return 0.0
min_val = min(ints)
max_val = max(ints)
if min_val == max_val:
return 0.0
remaining = [value for value in ints if value != min_val and value != max_val]
if not remaining:
return 0.0
return sum(remaining) / len(remaining)