Created
September 8, 2017 01:17
-
-
Save jonathanmcmahon/512c793c239dca89e88252b63fca5a1a to your computer and use it in GitHub Desktop.
Iterate over the upper triangular diagonals in a matrix
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""Iterate over the upper triangular diagonals in a matrix.""" | |
def n_by_n_matrix(n): | |
return [range(i*n,(i*n)+n)for i in range(n)] | |
def upper_tri_diagonal_iter(matrix): | |
result = [] | |
for diag in range(0, len(matrix)): | |
for row in range(0, len(matrix)-diag): | |
col = row + diag | |
result.append(matrix[row][col]) | |
return result | |
m = n_by_n_matrix(4) | |
print(m) | |
result = upper_tri_diagonal_iter(m) | |
assert result == [0, 5, 10, 15, 1, 6, 11, 2, 7, 3] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
in python3 convert the range to list