def diagonalDifference(arr,n):
left,right,i=0,0,0
while i != n:
left+=arr[i][i]
right+=arr[i][n-1-i]
i+=1
return abs(left-right)
I'm new to Python. What is the syntax used in Line 4-5 (arr[i][i]
)?
def diagonalDifference(arr,n):
left,right,i=0,0,0
while i != n:
left+=arr[i][i]
right+=arr[i][n-1-i]
i+=1
return abs(left-right)
I'm new to Python. What is the syntax used in Line 4-5 (arr[i][i]
)?
Basically you are using calculating the difference between the sum of diagonal values in a 2 dimensional array or a matrix of size (n x n).
So the matrix has n rows and n columns and u are using a value i to iterate over the diagonal values. arr[i] will return one entire row of the matrix with i in range from 0 to n - 1. For each row of size n we can access its members using arr[i][i] again where range of i is same
So basically for n = 5 your loop calculates sums of elements at index 00, 11, 22 , 33, 44 and for the other diagonal it uses 04, 13, 22, 31, 40