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
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With