규도자 개발 블로그

[해커랭크(Hackerrank)/Problem Solving/파이썬3(python3)] Diagonal Difference 본문

알고리즘/풀이

[해커랭크(Hackerrank)/Problem Solving/파이썬3(python3)] Diagonal Difference

규도자 (gyudoza) 2019. 3. 9. 15:12

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

For example, the square matrix  is shown below:

1 2 3
4 5 6
9 8 9  

The left-to-right diagonal = . The right to left diagonal = . Their absolute difference is .

Function description

Complete the  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, , the number of rows and columns in the matrix 
Each of the next  lines describes a row, , and consists of  space-separated integers .

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

Note: |x| is the absolute value of x

풀이

#!/bin/python3

import math
import os
import random
import re
import sys

# Complete the diagonalDifference function below.
def diagonalDifference(arr):
    max_index = len(arr) - 1
    sum_of_to_right = 0
    sum_of_to_left = 0
    for index in range(len(arr)):
        to_right_index = index
        to_left_index_row = max_index - index
        to_left_index_col = index
        sum_of_to_right = sum_of_to_right + arr[to_right_index][to_right_index]
        sum_of_to_left = sum_of_to_left + arr[to_left_index_col][to_left_index_row]
    return abs(sum_of_to_right - sum_of_to_left)

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    n = int(input())

    arr = []

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

    result = diagonalDifference(arr)

    fptr.write(str(result) + '\n')

    fptr.close()

설명

숫자로 이뤄진 정사각형의 2차원배열이 주어진다. 해당 배열에서 좌상->우하로 향하는 요소들의 숫자들을 전부 더한한 값을 A, 우상->좌하로 향하는 요소들의 숫자들을 전부 더한 값을 B라고 했을 시에 A - B = |X|. 여기에서 X는 절대값(abs). 절대값은 음양의 개념이 없는 0이라는 기준에서 얼만큼 떨어져있는 숫자인지를 나타내는 값이라고 생각하면 쉽다. 15도 +15도 전부 0에서 15만큼 떨어져있으니 15인 것이다. 이것도 싫다면 -를 떼기만 하면 된다.

 훨씬 간단하게 구현할 수도 있지만 이해와 가독성을 위해 위의 형태를 취했다. to_right_index는 좌상에서 우하로 향하는 숫자들의 색인이고 to_left_index는 우상에서 좌하로 향하는 숫자들의 색인이다.


Comments