Home > database >  Mini-Max Sum Coding Challenge Python
Mini-Max Sum Coding Challenge Python

Time:01-04

I worked on this coding question as practice earlier: "Given five positive integers, find the minimum and maximum values that can be calculated by summing exactly four of the five integers. Then print the respective minimum and maximum values as a single line of two space-separated long integers."

I have a tendency to overcomplicate things. This is my solution and after researching I found how simple the actual solution was. What are some tips on thinking of the best minimalistic approach to a problem?

#My solution
def miniMaxSum(arr):
    countList = []
    currentIndex = 0
    max_sum = 0
    min_sum = 0
    for i in range(len(arr)):
        for j, number in enumerate(arr):
            if j != currentIndex:
                    countList.append(number)
        if sum(countList) > max_sum:
            max_sum = sum(countList)
        if i == 0:
            min_sum = sum(countList)
        elif sum(countList) < min_sum:
            min_sum = sum(countList)
        currentIndex  = 1
        countList = []
    print(min_sum, max_sum)
    
if __name__ == '__main__':

    arr = list(map(int, input().rstrip().split()))

    miniMaxSum(arr)

CodePudding user response:

An alternative solution, if you prefer:

def miniMaxSum(arr):
    mini = min(arr)
    maxi = max(arr)

    mini_sum = sum(arr) - maxi
    maxi_sum= sum(arr)-mini

    print(f'The minimum sum is {mini_sum}, the maximum sum is {maxi_sum}')



miniMaxSum([2,1,3,10,4])   

The output (for clarity I have changed the print requirement): enter image description here

Not sure if this avoids sorting by using min and max functions, but if it didn't you could loop through and accomplish it with the sort. BrokenBenchmark's answer is the most concise of course though.

CodePudding user response:

This problem can be solved using sorted(), list slicing, and sum() (This is the simplest solution if "simple" == "minimizing number of lines of code", though this principle isn't always true):

print(sum(sorted(input_list)[:-1]), sum(sorted(input_list[1:])))

In general, you shouldn't try to aim for exactly matching a posted solution on your first try. You are solving the problem for the first time, while the solution likely has been edited, revised, refactored, etc.. Improving your ability to write simpler solutions often comes from exposure to similar problems and experience with using various language features, which takes takes time and practice.

  •  Tags:  
  • Related