0

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?

4
  • What have you thought of? Commented Jan 10, 2021 at 15:28
  • @Gulzar I don't know. As far as I know, they're supposed to return the same value. Commented Jan 10, 2021 at 15:31
  • Just eye-balling it, I'd guess that you are not including the last index that you want. Commented Jan 10, 2021 at 15:31
  • 1
    Would say you need [j:j+3] rather than [j:j+2] (i.e. slice is not inclusive of the right end point). Commented Jan 10, 2021 at 15:36

2 Answers 2

2

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)
Sign up to request clarification or add additional context in comments.

Comments

2

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.