Skip to content Skip to sidebar Skip to footer

Python - How To Get The Sum Of The Upper Triangle Of A Matrix Without Using Numpy?

This question is similar to this one but I want to know how to do this without using numpy. How can I get the summer of the upper triangle of a matrix with pure Python? So for ex

Solution 1:

For square matrices: Actually I think it behaves correctly even for non-square matrices.

>>> m
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> sum(( m[i][i+1:] for i in range(len(m)) ), [])
[2, 3, 6]
>>> sum(( m[i][:i] for i in range(len(m)) ), [])
[4, 7, 8]

(Using the sum-flatten hack)

>>> sum([[1, 2], [3, 4]], [])
[1, 2, 3, 4]

Solution 2:

There is example of code:

matrix = [[1,  2,  3],
          [4,  5,  6],
          [7,  8,  9]]upper = []
lower = []
for j in xrange(0, len(matrix)):
    for i in xrange(0, len(matrix)):
        if j>i:
            lower.append(matrix[j][i])
        elif j<i:
            upper.append(matrix[j][i])
        else:
            pass
upperSum = sum(upper)
lowerSum = sum(lower)

Solution 3:

Bear in mind that this will only work if every sub array has the same length.

defGetSum(array):
    total = 0#Set the default value of "total" to 0.for i inrange(len(array)):
    #for every item in the array:
        total += array[i]
        #Append the current selected value in the array to the total.return total
    #Return the totaltry:
    length = len(matrix)
    #Get the length of the "matrix" array.
    rowlength = len(matrix[0])
    #Get the length of rows (the sub arrays within the main array).
    upper = [matrix[0][rowlength-2],matrix[0][rowlength-1],matrix[1][upperlength-1]]
    #Get the upper corner of the matrix array.
    uppersum = GetSum(upper)
    #Get the sum of all the items in "upper".
    lower = [matrix[length-2][0],matrix[length-1][0],matrix[length-1][1]]
    #Get the lower corner of the matrix array.
    lowersum = GetSum(lower)
    #Get the sum of all the items in "lower".except:
    print("Incorrect matrix dimensions :/")
    #print an error message

Solution 4:

upper = []
[upper.extend(matrix[i][i+1:]) for i in range(len(matrix))]
lower = []
[lower.extend(matrix[i][0:i]) for i in range(len(matrix))]

And then do sum :-)

Solution 5:

One-liner with sum and generator expression:

matrix = [[1,  2,  3],
          [4,  5,  6],
          [7,  8,  9]]

size = 2
sum(sum(matrix[i][-size+i:]) for i in xrange(size)) # 11sum(sum(matrix[-i-1][:size-i]) for i in xrange(size)) # 19

Post a Comment for "Python - How To Get The Sum Of The Upper Triangle Of A Matrix Without Using Numpy?"