Diagonal Difference
Given a square matrix, calculate the absolute difference between the sums of its diagonals.
Input Format
The first line contains a single integer, denoting the number of rows and columns in the matrix .
The next lines denote the matrix 's rows, with each line containing space-separated integers describing the columns.
The next lines denote the matrix 's rows, with each line containing space-separated integers describing the columns.
Constraints
Output Format
Print the absolute difference between the sums of the matrix's two diagonals as a single integer.
Sample Input
3
11 2 4
4 5 6
10 8 -12
Sample Output
15
Explanation
The primary diagonal is:
11
5
-12
Sum across the primary diagonal: 11 + 5 - 12 = 4
The secondary diagonal is:
4
5
10
Sum across the secondary diagonal: 4 + 5 + 10 = 19
Difference: |4 - 19| = 15
Difference: |4 - 19| = 15
Note: |x| is the absolute value of x
Solution:
Python Code
#!/bin/python3 import os import sys # # Complete the diagonalDifference function below. # def diagonalDifference(a): # # Write your code here. # sum1=sum(a[i][i] for i in range(n)) sum2=sum(a[i][n-i-1] for i in range(n)) return abs(sum1-sum2) if __name__ == '__main__': f = open(os.environ['OUTPUT_PATH'], 'w') n = int(input()) a = [] for _ in range(n): a.append(list(map(int, input().rstrip().split()))) result = diagonalDifference(a) f.write(str(result) + '\n') f.close()
Comments
Post a Comment