Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Minimum and maximum sums from a list Python

I've been doing problems on HackerRank to get my foot in the door for solving Python problems and while I've had fun working through a few, one problem is stumping me.

This problem is the Mini-Max sum, which takes an input(arr); an array of 5 integers, and prints the sum of the biggest and smallest 4 integers from arr in the next line's format via miniMaxSum(arr)

maximum minimum

e.g. miniMaxSum(1, 2, 3, 4, 5)

10 14

I've done something which you can find below that works with this, and most examples to return the desired results, but I've just found out that it doesn't work for arr = (5, 5, 5, 5, 5). I suspect that this is because when the maximum value is identical to another value in the list (e.g. arr = 1, 2, 3, 4, 4) or likewise for minimum (e.g. arr = 1, 1, 3, 4, 5), my code simply fails as it relies on nothing being the same as arr's biggest or smallest value. The HackerRank error message is "Wrong Answer" if that helps.

Please critique and suggest improvements so it works with any array of 5 integers (e.g. (5, 5, 5, 5, 5)). I am keen in understanding how this works and your help would be immensely appreciated. Thanks in advance!

# Complete the miniMaxSum function below.
def miniMaxSum(arr):
    listmax = []
    listmin = []
    for number in arr:
        if number > min(arr):
            listmax.append(number)    
    for number in arr:
        if number < max(arr):
            listmin.append(number)
    maxnum = sum(listmax)
    minnum = sum(listmin)
    print (minnum, maxnum)
like image 578
John Carter Avatar asked Apr 10 '26 15:04

John Carter


1 Answers

Since it's a really small list, I would just sort it and then pick off the first-5 and then the last 5 and take the sums of those, respectively.

def miniMaxSum(arr):
  arr_sorted = sorted(arr)
  return sum(arr_sorted[:4]), sum(arr_sorted[-4:])

print(miniMaxSum([1,2,3,4,5]))
print(miniMaxSum([5,5,5,5,5]))

Output:

>>> print(miniMaxSum([1,2,3,4,5]))
(10, 14)
>>> print(miniMaxSum([5,5,5,5,5]))
(20, 20)
like image 75
booleys1012 Avatar answered Apr 12 '26 05:04

booleys1012



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!