0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【python】対角線上の合計数値の差分を求めるプログラム

Posted at

#【python】対角線上の合計数値の差分を求めるプログラム

自分用のメモです。

▼設問

  • n × n の表が与えられる。
  • 左上から右下までの合計値と右上から左下までの差分の絶対値を求める。

URL

▼sample input

matrix
11 2 4
4 5 6
10 8 -12
arr = [[11,2,4],[4,5,6],[10,8,-12]]

▼sample output

15

▼my answer

def diagonalDifference(arr):
    n = len(arr[0])-1
    xrr=[]
    yrr=[]

    i=0
    for ar in arr:
        xrr.append(ar[i])
        yrr.append(ar[n-i])
        i += 1
    ans = abs(sum(xrr)-sum(yrr))
    return ans

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()

**・abs()** 絶対値を返す

・listの定義はまとめられない
初期値で i = x = 0とする感覚で、listは定義できない。
☓xrr = yrr = [] ※同じ一つのオブジェクトを参照してしまう。
◯xrr=[] yrr=[]

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?