Sum of an array while ignoring one minimum and one maximum

Viewed 254

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?

6 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)
return sum(sorted(arr)[1:-1])

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

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

You can convert your list into set i. e set(arr) then you will get the unique elements. Now you can igmore max and minimum and get some of all elements. Do let me know if you need code.

from collections import Counter
arr = [6, 0, 1, 10, 10]

def my_sum(arr = list()):
    arr.sort()
    c = Counter(arr)
    cur_min = arr[0]
    cur_max = arr[-1]

    my_sum = sum(arr) - cur_min * (c.get(cur_min)- 1) - cur_max * (c.get(cur_max) - 1)
    return my_sum


### in case of large arrays avoiding the sort: 
def my_sum2(arr = list()):
    cur_min = arr[0]
    cur_max = arr[0]
    c = Counter()
    res = 0
    for x in arr:
        cur_min = min(cur_min, x)
        cur_max = max(cur_max, x)
        c[x] += 1
        res += x

    res = res - cur_min * (c.get(cur_min) - 1) - cur_max * (c.get(cur_max) - 1)
    return res


print(my_sum(arr))
print(my_sum2(arr))

It won't ignore duplicates between cur_min and cur_max.

This works. Remove maximum and minimum values from the list and compute sum

a = [6, 0, 1, 10, 10]
maximum = max(a)
minimum = min(a)
a = list(filter((maximum).__ne__, a))
a = list(filter((minimum).__ne__, a))

print(sum(a)+maximum+minimum)

if you do not want to modify input list, then use a_copy = a.copy() and use a_copy in place of a

Related