Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - How to get the sum of the upper triangle of a matrix without using numpy?

Tags:

python

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 example, I have

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

How could I return:

upper = [2,3,6]
upperSum = 11
lower = [4,7,8]
lowerSum = 19
like image 587
Jaromjj Avatar asked Sep 16 '25 15:09

Jaromjj


1 Answers

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]
like image 112
pacholik Avatar answered Sep 18 '25 08:09

pacholik