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
import numpy as np
import os
def Sum_Non_Diag(A,N):
  sum1=0
  sum2=0
  sum3=0
  sum4=0
  for r in range(N):
    for c in range(N):
      if r + c < N - 1:
        if(r < c and r != c and r + c):
          sum1 += A[r][c]
        elif r != c:
          sum2 += A[r][c]
      else:
        if r > c and r + c != N - 1:
          sum3 += A[r][c]
        else:
          if r + c != N - 1 and r != c:
            sum4 += A[r][c]
  return (sum1 + sum2 + sum3 + sum4)
Â
x = [[4,1,3],[2,5,6],[1,2,3]]
N=(np.array(x).shape)
if(N[0]==N[1]):
  print(Sum_Non_Diag(x, N[0]))
Comments
Leave a comment