I am working on a HackerRank problem and I don't understand some of the logic:
if (i == j):
left += a[i][j]
The above is saying if the row/column indices are the same([1,1], [2,2], [3,3]), append value found at those coordinates to the list 'left'
I don't understand the logic in the code below. To me it looks like it's saying append values found at the coordinates where row index + column index = 3 (n-1) but I don't think that's right. What would the code below translate to?
if (i + j) == (n - 1):
right += a[i][j]
Below is the function with sample inputs a and n.
a = [[ 1, 2, 3, 4 ],
[ 5, 6, 7, 8 ],
[ 1, 2, 3, 4 ],
[ 5, 6, 7, 9 ]]
n = 4
def xsum(a, n):
left = 0
right = 0
for i in range(0, n):
for j in range(0, n):
if (i == j):
left += a[i][j]
if (i + j) == (n - 1):
right += a[i][j]
return (abs(left-right))
What would the code below translate to?
The code leverages the fact that an element is on the right diagonal if and only if the row and column indices sum to n - 1
. It then adds the value at the given (i, j)
pair to right
.
This can be visualized using the following matrix: each entry is the sum of its row and column index:
print([[i + j for i in range(4)] for j in range(4)])
#[[0, 1, 2, 3],
# [1, 2, 3, 4],
# [2, 3, 4, 5],
# [3, 4, 5, 6]]
# (notice that the n - 1 == 3, and the 3s are only on the antidiagonal!)
This is a question about correctness, which is distinct from efficiency. If you're wondering whether this code is efficient, the answer is no: see Chris's answer.