Like a Star

HackerRank Diagonal Difference 본문

PL/Python

HackerRank Diagonal Difference

junmosdata 2022. 8. 8. 07:41

Quiz.

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 = 1 + 5 + 9 = 15.

The right to left diagonal = 3 + 5 + 9 = 17.

Their absolute difference is |15 - 17| = 2.

 

Sample Input)

3
11 2 4
4 5 6
10 8 -12

Sample Output)

15

Raw Source)

#!/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

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

    n = int(input().strip())

    arr = []

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

    result = diagonalDifference(arr)

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

    fptr.close()

 

처음 입력하는 값은 정방행렬의 행렬 길이이다.

3을 입력했다면, 3행 3열인 행렬을 입력한다는 것을 의미한다.

그 다음에는 각 행에 들어가는 값을 입력해준다.

그 때, 두 개의 대각선에 해당하는 값들의 합의 차를 구하는 것이 문제이다.

그렇기 때문에 대각선이 가지는 규칙이 무엇인지에 집중해야 한다.

 

\ 대각선과 / 대각선을 각각 1대각선, 2대각선이라고 하겠다.

3x3 행렬을 예로 들어서 1대각선을 보면, 각 인덱스가 (0, 0), (1, 1), (2, 2)인 것을 확인할 수 있다.

즉, 행과 열이 같은 인덱스를 모두 찾아 더해주면 첫 번째 대각선의 합을 구할 수 있다.

 

2대각선은 (0, 2), (1, 1), (2, 0)이다.

행렬의 인덱스 합이 2라는 것을 알 수 있다.

즉, '행렬의 길이 - 1'과 인덱스의 합이 같은 값을 찾으면 된다.

 

이 두개의 규칙들로 두 개의 값을 구하고 차를 구한다.

유의할 것은, '절대값'으로 출력해줘야 한다.

따라서 abs() 함수로 절대값을 구해서 출력하면 원하는 결과를 얻을 수 있다.

 

My Source)

def diagonalDifference(arr):
    # Write your code here
    a1, a2 = 0, 0
    for i in range(len(arr)):
        for j in range(len(arr)):
            if i == j:
                a1 += arr[i][j]
            if i + j == len(arr) - 1:
                a2 += arr[i][j]
    res = abs(a1 - a2)
    return res

'PL > Python' 카테고리의 다른 글

HackerRank Write a function  (0) 2022.08.09
HackerRank Compare the Triplets  (0) 2022.08.05
HackerRank Python If-Else  (0) 2022.08.05
백준 18108번 1998년생인 내가 태국에서는 2541년생?!  (0) 2022.08.03
백준 10869번 사칙연산  (0) 2022.08.02
Comments