0

I can't seem to find anything about adding both diagonals in a 4x4 array.

row = 4
column = 4
lis1 = [23.5, 30.1, 56.2, 11.9]
lis2 = [45.1, 8.9, 77.3, 54.1]
lis3 = [6.6, 7.7, 8.8, 2.2]
lis4 = [9.9, 8.9, 7.8, 23.6]
array = [lis1, lis2, lis3, lis4]

def diagonalSum(array):
    count = 0
    for i in range (len(array)):
        count += array[i][i]
    print ('The total of the elements in both diagonals equals  %.2f' %(count))
    return count

When I call on the function, it prints the total for lis1[0]+lis2[1]+lis3[2]+lis4[3] but I need it to also calculate the total for lis4[0]+lis3[1]+lis2[2]+lis1[3] and display the total of both diagonals. Any suggestions?

1 Answer 1

1

You are only counting the diagonal from the top left to the bottom right, in this case 0,0 1,1 2,2 3,3. You also need to count the other diagonal from the top right to the bottom left, or 0,3 1,2 2,1 3,0

To use one loop you could add another index that you increment or decrement yourself, something like this

j = len(array) - 1
for i in range(len(array)):
    # diagonal from top left to bottom right
    count += array[i][i]
    # diagonal from bottom left to top right
    count += array[j][i]
    j -= 1
Sign up to request clarification or add additional context in comments.

1 Comment

I knew it had to be something obvious... brain is just fried. Thank you for the help.

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.