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?
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
.
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. This will go out of bound since your arr
can index only upto arr[i][n-1]
. So, This is giving you list index out of range
error.
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]
. So, when i = 0
your second index becomes n
, that is out of bounds as it tries to access arr[0][n]
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.