Matrix Triangle Sum :
Question
Yash is solving a matrix problem as a part of his preparation for an entrance exam. In the problem, a Square Matrix of size N * N is given. You need to calculate the sum of upper and lower triangular elements.
Upper triangle consists of elements on the anti-diagonal and above it
whereas,
Lower triangle consists of elements on the anti-diagonal and below it.
Write a program to solve Yash's Matrix problem.
Input:
The first line of input is an integer N.
The next N lines consists of N space-seperated integers.
Output:
The first line of output should be the sum of elements on the upper triangle.
The second line of output should be the sum of elements on the lower triangle.
Sample Input 1:
3
1 2 3
4 5 6
7 8 9
Sample Output 1:
22
38
Sample Input 2:
5
6 7 5 1 4
6 8 5 1 8
1 1 1 5 1
5 7 5 8 8
8 3 5 8 8
Sample Output 2:
66
77
def calculateSum(matrix, r, c):
upperSum = 0
lowerSum = 0
for i in range(r):
for j in range(c-1,0,-1):
if (i >= j):
upperSum += matrix[i][j]
print(upperSum);
counter=0
# to calculate sum of lower
for i in range(r-1,-1,-1):
for j in range(counter,c):
lowerSum += matrix[i][j]
counter+=1
print(lowerSum)
R = int(input())
C = int(input())
matrix = []
for i in range(R):
arr = [int(i) for i in input().split()]
matrix.append(arr)
calculateSum(matrix, R, C)
Comments
Leave a comment