일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | |||||
3 | 4 | 5 | 6 | 7 | 8 | 9 |
10 | 11 | 12 | 13 | 14 | 15 | 16 |
17 | 18 | 19 | 20 | 21 | 22 | 23 |
24 | 25 | 26 | 27 | 28 | 29 | 30 |
- 백준
- 맥북
- programmers
- dacon
- github
- Git
- ChatGPT
- Docker
- 데이콘
- Baekjoon
- 프로그래머스 파이썬
- 금융문자분석경진대회
- hackerrank
- 자연어처리
- 파이썬
- leetcode
- 코로나19
- 캐치카페
- 편스토랑
- gs25
- ubuntu
- Real or Not? NLP with Disaster Tweets
- AI 경진대회
- 편스토랑 우승상품
- 더현대서울 맛집
- 우분투
- SW Expert Academy
- 프로그래머스
- Kaggle
- PYTHON
- Today
- Total
솜씨좋은장씨
[HackerRank] Diagonal Difference (Python) 본문
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 [ i ], and consists of n space-separated integers arr [ i ][ 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
'Programming > 코딩 1일 1문제' 카테고리의 다른 글
[SW_Expert_Academy] 7701번 염라대왕의 이름 정렬 (Python) (0) | 2020.03.17 |
---|---|
[HackerRank] Plus Minus (Python) (0) | 2020.03.16 |
[HackerRank] Dictionaries and Hashmaps: Two Strings (Python) (0) | 2020.03.14 |
[HackerRank] Arrays: Array Manipulation (Python) (0) | 2020.03.13 |
[leetCode] 58. Length of Last Word (Python) (2) | 2020.03.12 |