这个Python Hackerrank函数是如何工作的?



我在编程方面是一个完全的初学者,我刚刚开始学习我的第一门语言,即Python。最近,我一直在练习解决Hackerrank中的问题,我被困在一些"对角线差"问题上。

这个问题对我来说是全新的,所以我在网上搜索一些答案,并遇到了有人在 github 中制作的这个功能。


def diagonalDifference(arr):
prim =0
sec=0
length = len(arr[0])
i=0                           #what does i=0 even do here?
for count in range(length):
prim += arr[count][count] #don't understand what "[count][count]" mean
sec += arr[count][(length-count-1)] #don't understand this either
return abs(prim-sec)

这是相同的代码,有进一步的解释。基本上这个函数对元素求和 左上角到右下对角线以 prim 和总和存储运行总计 右上角到左下角线的元素以秒为单位存储运行总计。然后 返回差值的绝对值。对于数组,索引为:arr[row][column] 从 0 到比数组长度小 1。希望对你有帮助

import numpy as np
def diagonalDifference(arr):
prim = 0
sec = 0
length = len(arr[0])
for i in range(length):
print("Iteration:", i,
"UL to BR Diagonal:", arr[i][i],
"UR to BL Diagonal:", arr[i][(length-i-1)])
# Get value of arr in the ith row and ith column (i.e. the UL to BR diagonal)
# Add to the cummulative sum
prim = prim + arr[i][i]
# Get the value of arr in the ith row and the (length-i-1)th column
# Columns traverse right to left (i.e. the UR to BL diagonal)
sec = sec + arr[i][(length-i-1)]
print("UL to BR Diagonal Sum:", prim,
"----",
"UR to BL Diagonal Sum:", sec)
# Take the absolute value of the difference between the running totals
return abs(prim-sec)
a = np.array([[1, 2, 4], [3, 4, 6], [3, 8, 1]])
print(a)
diagonalDifference(a)

输出:

[[1 2 4]
[3 4 6]
[3 8 1]]
Iteration: 0 UL to BR Diagonal: 1 UR to BL Diagonal: 4
Iteration: 1 UL to BR Diagonal: 4 UR to BL Diagonal: 4
Iteration: 2 UL to BR Diagonal: 1 UR to BL Diagonal: 3
UL to BR Diagonal Sum: 6 ---- UR to BL Diagonal Sum: 11

首先,这里的i是不必要的。现在,假设我们有一个方阵:

arr = 
[[1, 2, 4],
[3, 5, 8],
[6, 2, 1]]
The indices will be:
[[(0,0), (0,1), (0,2)],
[(1,0), (1,1), (1,2)],
[(2,0), (2,1), (2,2)]]

所以主要对角线是[(0,0),(1,1),(2,2)]第二对角线是:[(0,2),(1,1),(2,0)]

现在在函数中:

length = len(arr[0])
arr[0] is := [1, 2, 4], i.e. the first row,
so length = 3
for count in range(length):
so count will have values: [0, 1, 2]
Now, for all the iterations:
arr[count][count] will yield: arr[0][0], arr[1][1] and arr[2][2],
hence giving the first diagonal.
And 
arr[count][(length-count-1)] will yield: arr[0][(3-0-1)], arr[1][(3-1-1)],
and arr[2][(3-2-1)], i.e arr[0][2], arr[1][1] and arr[2][0],
which is the second diagonal

最新更新