Sovietsperm
Sovietsperm

Reputation: 21

Why python sum() function doesn't work in this case?

The prompt for the question is linked here:Hourglass sum in 2D array

I have written 2 different codes that are supposed to output the same thing.

Code1

def hourglassSum(arr):
    total = []
    for i in range(0, 4):
        for j in range(0, 4):
            total.append(arr[i][j] + arr[i][j+1] + arr[i][j+2] + arr[i+1][j+1] + arr[i+2][j]+ arr[i+2][j+1]+ arr[i+2][j+2])
    return max(total)

Code2

def hourglassSum(arr):
    total = []
    for i in range(0, 4):
        for j in range(0, 4):
            total.append(sum(arr[i][j:j+2]) + arr[i+1][j+1] + sum(arr[i+2][j:j+2]))
    return max(total)

The 2nd code outputs a different value. Can anyone tell me what went wrong?

Upvotes: 0

Views: 278

Answers (2)

Dominic van der Pas
Dominic van der Pas

Reputation: 142

Let arr = [[1, 2, 3]] for this example.

sum(arr[0][0:2]) = 3 because we are summing 1 and 2.

sum(arr[0][0:3]) = 6 because we are summing 1, 2 and 3.

So the answer to your question is that [j:j+2] does not include j+2. You want to use [j:j+3]

Upvotes: 2

Bram Vanroy
Bram Vanroy

Reputation: 28554

You forgot to include the not-included index. A slice has the format of start:end where the end integer is not included. So you have to do a +1 when converting from indices to a slice.

def hourglassSum1(arr):
    total = []
    for i in range(0, 4):
        for j in range(0, 4):
            total.append(arr[i][j] + arr[i][j+1] + arr[i][j+2] + arr[i+1][j+1] + arr[i+2][j]+ arr[i+2][j+1]+ arr[i+2][j+2])
    return max(total)

def hourglassSum2(arr):
    total = []
    for i in range(0, 4):
        for j in range(0, 4):
            # Use +3
            total.append(sum(arr[i][j:j+3]) + arr[i+1][j+1] + sum(arr[i+2][j:j+3]))
    return max(total)


l = [[1, 1, 1, 0, 0, 0],
     [0, 1, 0, 0, 0, 0],
     [1, 1, 1, 0, 0, 0],
     [0, 0, 0, 0, 0, 0],
     [0, 0, 0, 0, 0, 0],
     [0, 0, 0, 0, 0, 0]]

assert hourglassSum1(l) == hourglassSum2(l)

Upvotes: 2

Related Questions