Coders Packet

FIND ABSOLUTE DIFFERENCE BETWEEN MAIN AND ANTI DIAGONAL OF MATRIX USING PYTHON

By Yuvraj Singh

In this tutorial, we will calculate the absolute difference between both diagonal using python

What is a matrix?

matrix is a rectangular array of numbers or expressions, arranged in rows and columns. A matrix with m rows and n columns is called m x n matrix or m-by-n matrix. i.e. matrix M

{\displaystyle {\begin{bmatrix}9&13&5\\1&11&7\\2&6&3\end{bmatrix}}}3x3

An individual item of a matrix is called element. (i.e. 1 is an element of matrix)

A matrix with single row is called row vector. (i.e. [9  13  5] is a row vector)

A matrix with single column is called column vector. (i.e. [9  1  2] is a column vector)

The main diagonal of a square matrix (where m = n, means number of rows and columns are equal) Mi x j is the list of entries, where i = j.

(main diagonal element of a matrix M is 9, 13, 3)

The anti diagonall of a square matrix Mi x j is the list of entries, where i + j = N (N is number of rows or columns).

(anti diagonal element of matrix M is 5, 11, 2).

 

Absolute Difference the distance between two numeric values, disregarding whether this is positive or negative. (i.e. absolute difference between 2 and 6 or 6 and 2 is 4.)

CODE:
 

n = int(input().strip())
arr = []

for _ in range(n):
    arr.append(list(map(int, input().rstrip().split())))

def diagonalDifference(arr):
    abs_diff = 0
    left_diag = 0
    right_diag = 0
    k = len(arr) - 1

    for i in range(len(arr)):
        left_diag += arr[i][i]
        right_diag += arr[i][k]
        k -= 1

    abs_diff = abs(right_diag - left_diag)
      return abs_diff

result = diagonalDifference(arr)
print(result)

Example:

Input:

3

9 13 5
1 11 7
2  6  3 
Output:
5

Download project

Reviews Report

Submitted by Yuvraj Singh (yuvrajeyes)

Download packets of source code on Coders Packet