Sum of Non-Diagonals
As the creative content member of your newspaper company, you are given the task to publish a puzzle in your local newspaper. For a given MxM integer matrix, the task is to print the sum of all elements other than the diagonal elements,Both the diagonals are to be excluded.
Input
The first line of input is a positive integer M.
The next M lines of input contain M space-separated integers.
Output
The output is an integer that represents the sum of all the numbers in the matrix as mentioned above.
Sample Input1
3
4 1 3
2 5 6
1 2 3
Sample Output1
11
Sample Input2
5
1 2 2 3 3
4 4 5 6 7
9 8 7 6 5
9 2 3 8 8
-4 -2 -2 4 -7
Sample Output2
63
def read_matrix():
m = int(input())
A = []
for i in range(m):
line = input()
row = [int(s) for s in line.split()]
A.append(row)
return A
def sum_non_diagonal(A):
m = len(A)
sum = 0
for i in range(m):
for j in range(m):
if i != j and i != m-1-j:
sum += A[i][j]
return sum
def main():
A = read_matrix()
print(sum_non_diagonal(A))
main()
Comments
Leave a comment