Skip to content

Instantly share code, notes, and snippets.

@jonathanmcmahon
Created September 8, 2017 01:17
Show Gist options
  • Save jonathanmcmahon/512c793c239dca89e88252b63fca5a1a to your computer and use it in GitHub Desktop.
Save jonathanmcmahon/512c793c239dca89e88252b63fca5a1a to your computer and use it in GitHub Desktop.
Iterate over the upper triangular diagonals in a matrix
"""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]
@morenoh149
Copy link

in python3 convert the range to list

def n_by_n_matrix(n):
    return [list(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