[Python] Diagonal difference in Python

Discussão em 'Python' iniciado por Stack, Março 26, 2025.

  1. Stack

    Stack Membro Participativo

    I am working on a HackerRank problem and I don't understand some of the logic:

    if (i == j):
    left += a[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[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[j]
    if (i + j) == (n - 1):
    right += a[j]
    return (abs(left-right))

    Continue reading...

Compartilhe esta Página