How to add diagonals of a matrix in Python 3.3.5

I am using numpy. My assignment:

"Write a function sumOfDiagonal, which has one parameter of a list of types. The list is a 4x4 two-dimensional array of integers (4 rows and 4 columns of integers). The function returns the sum of the integers in diagonal positions from left to right. The function should return 14 for the list below. You you can assume the list is always a 4x4 two dimensional integer array.4 9 2 5

3 1 10 6

7 2 5 1

8 8 1 4 "

I struggle with this very hard. I tried several approaches and got nothing. First I tried:

def sumOfDiagonal (list1: list):

 summation1=[i.split(", ")[0] for i in list1]

      

return (summation1)

print (sumOfDiagonal ([[4, 9, 2, 5], [3, 1, 10, 6], [7, 2, 5, 1], [8, 8, 1, 4,]])))

because I saw on another thread that maybe it could have been done, and I thought I could split the input array into separate lists for a useful first run, but I got an error about attribute missing ... I just tried again. and I got an error about calling an external function

Then I made several other attempts in a different direction. Now I have:

def sumOfDiagonal (list1: list):

i=0
j=0
summation1=0
for row in list1:
    for i in row:

        for column in list1:
            for j in column:

                summation1=list1[i j],row[i]+summation1

      

return (summation1)

print (sumOfDiagonal ([[4, 9, 2, 5], [3, 1, 10, 6], [7, 2, 5, 1], [8, 8, 1, 4,]])))

This obviously doesn't work, but I had some version of this with no syntax errors before and only with a boolean error (it was outputting 44)

I think it was something like

def sumOfDiagonal (list1: list):

i=0
j=0
summation1=0
summation2=0
for row in list1:
    summation1=row[1]+summation1
    i+=i

for column in list1:
    summation2=column[i]+summation2
    i+=i

      

return (summation1 + summation2)

print (sumOfDiagonal ([[4, 9, 2, 5], [3, 1, 10, 6], [7, 2, 5, 1], [8, 8, 1, 4,]])))

I'm even close to being right, and how can I fix the massive bunch of failures I have?

Thank you very much in advance

+3


source to share


2 answers


When I find a matrix trace by hand, I first look at the top left and then add it to the second element in the second row, then to the third element in the third row, etc. This will help us here. This can be a good source of programming logic - if you can do it manually, you can program it.

In short, I think you have overdone it. Here are two options, assuming a list of lists like your example.

def sumOfDiagonal(matrix):
    sum = 0
    for i in range(len(matrix)):
        sum += matrix[i][i]        #These are the diagonal elements
    return sum

      



Or alternatively, if you want to do it all at once and search range(len(x))

for non-pythonic,

def sumOfDiagonal2(matrix):
    return sum([matrix[i][i] for i,_ in enumerate(matrix)])

      

+1


source


There are many ways to do this:

Starting with a multi-line string, parsing, diagonal selection, and summing can be done in one line:

txt = """4 9 2 5
3 1 10 6
7 2 5 1
8 8 1 4"""
sum([int(x.split()[i]) for i,x in enumerate(txt.splitlines())])

      

Or split the steps:

getting a list of lists by splitting strings

LOL = [[int(y) for y in x.split()] for x in txt.splitlines()]
# [[4, 9, 2, 5], [3, 1, 10, 6], [7, 2, 5, 1], [8, 8, 1, 4]]

      

and sum the diagonal

sum(v[i] for i,v in enumerate(lol))
# 14

      



If that's really the destination numpy

, genfromtxt

is a handy tool to get an array from txt

X=np.genfromtxt(txt.splitlines())
#
array([[  4.,   9.,   2.,   5.],
       [  3.,   1.,  10.,   6.],
       [  7.,   2.,   5.,   1.],
       [  8.,   8.,   1.,   4.]])

      

The array has its own function to get the diagonal and the sum

X.diagonal().sum()
# 14.0
X.trace()
np.einsum('ii',X)

      

Other iterations:

s = 0
for i in range(4): 
    s += X[i,i]
    # s += lol[i][i]

      

Or, if you want to iterate over both dimensions of the array:

s = 0
for i in range(4):
    for j in range(4):
        if i==j:   
            s += lol[i][j]

      

+1


source







All Articles