diagonal difference hackerrank solution in python 1

diagonal difference hackerrank solution in python

def diagonalDifference(arr):
    # Write your code here
    d1 =0
    d2=0
    for i in range(len(arr[0])):
        d1 += arr[i][i]
        d2 += arr[i][(len(arr[0])-i-1)]
    return abs(d1-d2)

Here is what the above code is Doing:
1. We are creating two variables d1 and d2 to store the sum of the diagonals.
2. We are iterating over the array using the range function.
3. We are adding the elements of the first diagonal to d1 and the elements of the second diagonal to d2.
4. We are returning the absolute difference between d1 and d2.

Similar Posts