0

I am attempting to solve this HackerRank question:

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.

Example

arr = [1, 2, 3, 4, 5]

The minimum sum is 1 + 3 + 5 + 7 = 16 and the maximum sum is 3 + 5 + 7 + 9 = 24

The function prints

16 24

Input Format

A single line of five space-separated integers.

Sample Input

1 2 3 4 5

Sample Output

10 14

Below is my code:

def miniMaxSum(arr):

    n = len(arr)
    results = []
    work_arr = arr

    for i in range(n):
        total = 0

        work_arr[i] = 0

        print(work_arr)

        for y in range(n):
            total = total + work_arr[y]

        # results.append(total)

        work_arr = arr

    # print(results)

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

Why does it output:

[0, 2, 3, 4, 5]
[0, 0, 3, 4, 5]
[0, 0, 0, 4, 5]
[0, 0, 0, 0, 5]
[0, 0, 0, 0, 0]

Instead of what I want, which is:

[0, 2, 3, 4, 5]
[1, 0, 3, 4, 5]
[1, 2, 0, 4, 5]
[1, 2, 3, 0, 5]
[1, 2, 3, 4, 0]

A revolving zero, but instead the zeros keep increasing

Why isn't the line work_arr = arr at the end of the iteration resetting the list back to the original that was passed to the function? Why does it keep adding zeros when I want it to just change that one at that index? And I do a reset at the end

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Helpfusali
  • 21
  • 5

1 Answers1

0

work_arr = arr copies reference only in python, so the two variables point to the same array and changing one would change the other.

What you want is a deep copy e.g. work_arr = arr[:] or work_arr = list(arr) that creates a new list in memory with the same values.

monk
  • 699
  • 5
  • 13