[英]IndexError: list index out of range for nested list (matrix)
I have been trying to solve a problem on HackerRank, and here is my solution for it, And I am receiving this error IndexError: list index out of range
on line 21, that is, s_sum += arr[i][n-1]
, can someone help me figure this out?我一直在尝试解决 HackerRank 上的一个问题,这是我的解决方案,我收到此错误
IndexError: list index out of range
on line 21,即s_sum += arr[i][n-1]
,有人可以帮我解决这个问题吗?
def diagonalDifference(arr):
p_sum = 0
s_sum = 0
for i in range(n):
p_sum += arr[i][i]
s_sum += arr[i][n-i]
return abs(p_sum - s_sum)
n = int(input().strip())
arr = []
for _ in range(n):
arr.append(list(map(int, input().rstrip().split())))
result = diagonalDifference(arr)
print(result)
When i = 0
, ie in the first iteration of the for
loop, ni
evaluates to n
, but that is out of bounds, if arr
is of size n
.当
i = 0
时,即在for
循环的第一次迭代中, ni
的计算结果为n
,但如果arr
的大小为n
,则超出范围。
When you loop -当你循环 -
for i in range(n):
p_sum += arr[i][i]
s_sum += arr[i][n-i]
Here, i starts from 0 and you have _sum += arr[i][n-1]
which will be arr[0][n]
in the first iteration.在这里,我从 0 开始,你有
_sum += arr[i][n-1]
这将是arr[0][n]
在第一次迭代中。 This will go out of bound since your arr
can index only upto arr[i][n-1]
.这将 go 超出范围,因为您的
arr
只能索引到arr[i][n-1]
。 So, This is giving you list index out of range
error.所以,这给你
list index out of range
错误。
You should do it correctly as follows -您应该正确执行以下操作 -
for i in range(n):
p_sum += arr[i][i] #primary diagonal sum
s_sum += arr[i][(n-1)-i] #secondary diagonal sum. notice the indexing arr[i][n-1-i]
#which ensures that the array doesn't access out of its bounds
Hope this helps !希望这可以帮助 !
You get out of range error because you run由于您运行,您超出范围错误
s_sum += arr[i][n-i]
for in the range [0:n-1]
.在
[0:n-1]
范围内。 So, when i = 0
your second index becomes n
, that is out of bounds as it tries to access arr[0][n]
.因此,当
i = 0
您的第二个索引变为n
时,这超出了它尝试访问arr[0][n]
的范围。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.