Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum of an array while ignoring one minimum and one maximum

Tags:

python

list

I have a program that finds the highest and lowest values in an array, excludes them, then sums up the rest of the numbers in that array. It works with most random inputs, except for cases when there are duplicates of the highest or the lowest number in that array

def sum_array(arr):
    if arr is None:
        return 0
    if len(arr) < 2:
        return 0
    return sum([i for i in arr if i != max(arr) and i != min(arr)])

In which case if I print(sum_array([6, 0, 1, 10, 10])), it only returns 7 instead of 17.

It excluded the highest number entirely.

How do I make the program recognize that there are duplicates and take just one of them for the sum so, in this case, it can return 17?

like image 286
Alteros Avatar asked Jul 01 '20 13:07

Alteros


3 Answers

You could just subtract the min and max from the overall sum, so it only counts as one occurrence:

a = [6, 0, 1, 10, 10]

sum(a) - max(a) - min(a)
like image 158
yatu Avatar answered Nov 15 '22 02:11

yatu


return sum(sorted(arr)[1:-1])

Just sort the array and sum every number except the first and the last.

like image 22
deceze Avatar answered Nov 15 '22 03:11

deceze


Perhaps this is what you are looking for. This is O(n) Time Complexity and O(1) Space Complexity.

def sum_array(arr):
    if arr is None or len(arr) < 2:
        return 0
    maximum = max(arr)
    minimum = min(arr)
    return sum(arr) - maximum - minimum
like image 40
Issei Avatar answered Nov 15 '22 04:11

Issei