-2

Print the absolute difference between the sums of the matrix's two diagonals as a single integer.

diagonalDifference(arr): sum1=0 sum2=0

for i in range(len(arr)):
    for j in range(len(arr)):
        if (i==j):
            sum1=sum1+arr[i][j]

        if (((i+j)-1)==(len(arr))):
            sum2=sum2+arr[i][j]
return abs(sum1-sum2)
P.s:

1 Answers1

1

your code is close, you just have the second if statement messed up, it should actually look like this:

for i in range(len(arr)):
    for j in range(len(arr)):
        if i==j:
            sum1 += arr[i][j]
        if i+j == len(arr)-1:
            sum2 += arr[i][j]

example:

arr = [[1,2,3],[4,5,6],[7,8,9]]
sum1 #15
sum2 #15
abs(sum1-sum2) #0

the length of the array is 3..... for the second diagonal, the first value is at i=2, j=0 so i+j = 2 which is 3-1 the second value is at i=1, j=1, so i+j = 2 which is 3-1...etc

Derek Eden
  • 4,403
  • 3
  • 18
  • 31
  • hey thankx for telling :) Actually i got bit confused with the representation of matrix like weather the ideal representation for 1*1 matrix is arr[01][02][03] or arr[11][12][13]. Can you update me about it – Divyansh Mishra Oct 28 '19 at 05:17