관리 메뉴

솜씨좋은장씨

[HackerRank] Diagonal Difference (Python) 본문

Programming/코딩 1일 1문제

[HackerRank] Diagonal Difference (Python)

솜씨좋은장씨 2020. 3. 15. 16:44
728x90
반응형

Given a square matrix, calculate the absolute difference between the sums of its diagonals.

For example, the square matrix arr is shown below:

1 2 3
4 5 6
9 8 9  

The left-to-right diagonal = 1 + 5 + 9 = 15. The right to left diagonal = 3 + 5 + 9 = 17. Their absolute difference is | 15 - 17 | = 2.

Function description

Complete the diagonalDifference function in the editor below. It must return an integer representing the absolute diagonal difference.

diagonalDifference takes the following parameter:

  • arr: an array of integers .

Input Format

The first line contains a single integer, n, the number of rows and columns in the matrix arr .
Each of the next n lines describes a row, arr [ ], and consists of n space-separated integers arr [  ][ j  ].

Constraints

  • -100 <= arr [ i  ][ j  ] <= 100

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

Note: |x| is the absolute value of x

 

Solution

#!/bin/python3

import math
import os
import random
import re
import sys

#
# Complete the 'diagonalDifference' function below.
#
# The function is expected to return an INTEGER.
# The function accepts 2D_INTEGER_ARRAY arr as parameter.
#

def diagonalDifference(arr):
    # Write your code here
    left_diagonal = 0
    right_diagonal = 0
    
    for i in range(len(arr[0])):
        left_diagonal = left_diagonal + arr[i][i]
        right_diagonal = right_diagonal + arr[i][len(arr[0])-i-1]

    answer = abs(left_diagonal - right_diagonal)

    return answer

 

 

SOMJANG/CODINGTEST_PRACTICE

1일 1문제 since 2020.02.07. Contribute to SOMJANG/CODINGTEST_PRACTICE development by creating an account on GitHub.

github.com

 

Comments