-2

Imagine I have an n x n matrix. I want to get the sum of each diagonal and print it to the user. For n=3 I can have

matrix =
[[1,2,3],
[1,2,3],
[1,2,3]]

I would get this printed:

sum1 = 3
sum2 = 5
sum3 = 6
sum4 = 3
sum5 = 1

I want to implement it in python. Thanks for helping!

1 Answers1

0

You can try like this :

import numpy as np
# Your Input
matrix =[[1,2,3],[1,2,3],[1,2,3]]
# Get Max : -> col
max_col = len(matrix[0])
# Get Max : -> row
max_row = len(matrix)
# Prepare the list of all diag value
fdiag = [[] for _ in range(max_row + max_col - 1)]
# Get all posible diag value 
for x in range(max_col):
    for y in range(max_row):
        fdiag[x+y].append(matrix[x][y])
# Output
for i in range (0,len(fdiag)): 
    print("sum"+str(len(fdiag)-i)+"="+str(sum(fdiag[i])))

Output:

sum5=1
sum4=3
sum3=6
sum2=5
sum1=3