# Hackerrank对角线差异，我的代码有什么问题？

##### 问题描述投票：-1回答：1

``````1 2 3
4 5 6
9 8 9
``````

diagonalDifference采用以下参数：

arr：一个整数数组。

``````3
11 2 4
4 5 6
10 8 -12
``````

``````15
``````

``````def diagonalDifference(arr):
i = 0
j = 0
left = 0
right = 0

for x in range(arr+1):
left += arr[0 + i][0 + j]
right += arr[0 + i][n - j]

i += 1
j += 1

return abs(left - right)
``````

``````def diagonalDifference(arr):
left = 0
right = 0
for x in range(len(arr)):
left += arr[0+x][0+x]
right += arr[0+x][len(arr)-x]
return abs(left-right)
``````

``````    right += arr[0+x][len(arr)-x]
IndexError: list index out of range
``````
python python-3.x
##### 1个回答
1

``````def diagonalDifference(arr):
left = 0
right = 0
for x in range(len(arr)):
left += arr[0+x][0+x]
right += arr[0+x][len(arr)-x]
return abs(left-right)
``````
``````arr = [[1,2],[3,4]]
len_arr = len(arr)   # len(arr) is 2, you index into  arr[0][2-0] fox x==0
# but arr only has arr[0][0] and arr[0][1] for x == 0
``````

``````k[0][0], k[1][1], k[2][2], ..., k[n-1][n-1]  where n = len(k) for the forward diag
``````

``````k[0][n-1-0], k[1][n-1-1], k[2][n-1-2], ..., k[n-1][n-1-(n-1)] for the backward diag
``````

Codewise：

``````def diag (data, reverse=False):
ld = len(data)
if reverse:
return sum(data[i][ld-i-1] for i in range(ld))
else:
return sum(data[i][i] for i in range(ld))

k = [[0,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15],[16,17,18,19,20],[0,22,23,24,25]]

print (diag(k))          # 64
print(diag(k,True))      # 44

def absDiagDiff(data):
return abs(diag(data)-diag(data,True))

print(absDiagDiff(k))    # 20
``````