Skip to content

Instantly share code, notes, and snippets.

@mwielondek
Last active August 29, 2015 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mwielondek/c1392eac6fe66cb1d427 to your computer and use it in GitHub Desktop.
Save mwielondek/c1392eac6fe66cb1d427 to your computer and use it in GitHub Desktop.
A function for diagonal matrix traversal. (python3)
def diag_trav_mat(mat,func):
# pretend to be working with a square matrix
# extend length to the largest of the sides
n = max(len(mat),len(mat[0]))
# for the amount of diagnoals
for x in range(0, 2*n-1):
# num of elements in diagonal
el = n - abs(n-1-x)
# row (i) range, the column (j) range is the same but reversed
r = range(min(x, n-1), min(x,n-1)-el,-1)
for i,j in zip(r, reversed(r)):
try:
# apply func to element
func(mat[i][j])
except IndexError:
# in case of non-square matrices
# we expect to get out of bounds
pass
### TEST CASES ###
# test matrix n = 2
m2 = [[1,3],[2,4]]
# test matrix n = 3
m3 = [[1,3,6],[2,5,8],[4,7,9]]
# test matrix n = 4
m4 = [[1,3,6,10],[2,5,9,13],[4,8,12,15],[7,11,14,16]]
# non square test matrix n = 2 m = 3
mn23 = [[1,3,5],[2,4,6]]
# non square test matrix n = 2 m = 3
mn32 = [[1,3],[2,5],[4,6]]
# print elements
diag_trav_mat(m3,print)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment