Answer to Question #311044 in Python for Manish

Question #311044

Matrix Triangle Sum

You are given a square matrix of size NxN, write a program to print the sum of upper and lower triangular elements.

Upper triangle consists of elements on the anti-diagonal and above it. The lower triangle consists of elements on the anti-diagonal and below it.


Explanation:

In the example,if the given matrix is

1 2 3

4 5 6

7 8 9

The upper triangle consists of elements on the anti-diagonal and above on it.

1 2 3

4 5

7

The sum of upper triangle elements is (1+2+3+4+5+7) equal to 22.


The lower triangle consists of elements on the anti-diagonal and below to it.

3

5 6

7 8 9

The sum of lower triangle elements is (3+5+6+7+8+9) equal to 38.

So the output should be

22

38


Sample Input

3 3

1 2 3

4 5 6

7 8 9


1
Expert's answer
2022-03-14T17:09:21-0400
def read_matrix(n):
    M = []
    for i in range(n):
        line = input()
        row = [int(s) for s in line.split()]
        M.append(row)
    return M


def sum_upper(M):
    n = len(M)
    sum = 0
    for i in range(n):
        for j in range(n-i):
            sum += M[i][j]
    return sum


def sum_lower(M):
    n = len(M)
    sum = 0
    for i in range(n):
        for j in range(n-1-i, n):
            sum += M[i][j]
    return sum


def main():
    line = input()
    n = int(line.split()[0])
    M = read_matrix(n)

    u = sum_upper(M)
    print(u)
    l = sum_lower(M)
    print(l)


if __name__ == '__main__':
    main()

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS