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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With