[Tutor] getting diagonals from a matrix

David Eccles (gringer) gmail at gringer.org
Tue Mar 2 23:54:13 CET 2010


I've managed to drum up some code to obtain a list containing joined diagonal
elements of a matrix (I'm making a word finder generator), but am wondering if
there's any better way to do this:

# setup so code snippet works properly
sizeW = 4
sizeH = 3
puzzleLayout = ['spam'] * (sizeW * sizeH)

# Starting with, say, an array with these indices:
# 0 1 2 3
# 4 5 6 7
# 8 9 A B

# I want the following items for a back diagonal (not in square brackets):
# [-2],[3],8 (+5) | div 4 = -1, 1, 2
# [-1],4,9 (+5)   | div 4 = -1, 1, 2
# 0,5,A (+5)      | div 4 =  0, 1, 2
# 1,6,B (+5)      | div 4 =  0, 1, 2
# 2,7,[C] (+5)    | div 4 =  0, 1, 3
# 3,[8],[D] (+5)  | div 4 =  0, 2, 3

# in other words, increase sequence by sizeW + 1 each time (sizeW - 1
# for forward diagonals), only selecting if the line you're on matches
# the line you want to be on

# back as in backslash-like diagonal
puzzleDiagBack = [(''.join([puzzleLayout[pos*(sizeW+1) + i] \
for pos in range(sizeH) if (pos*(sizeW+1) + i) / sizeW == pos])) \
for i in range(-sizeH+1,sizeW)]
puzzleDiagBackRev = [(''.join(reversed([puzzleLayout[pos*(sizeW+1) + i] \
for pos in range(sizeH) if (pos*(sizeW+1) + i) / sizeW == pos]))) \
for i in range(-sizeH+1,sizeW)]
# fwd as in forwardslash-like diagonal
puzzleDiagFwdRev = [(''.join([puzzleLayout[pos*(sizeW-1) + i] \
for pos in range(sizeH) if (pos*(sizeW-1) + i) / sizeW == pos])) \
for i in range(sizeW+sizeH-1)]
puzzleDiagFwd = [(''.join(reversed([puzzleLayout[pos*(sizeW-1) + i] \
for pos in range(sizeH) if (pos*(sizeW-1) + i) / sizeW == pos]))) \
for i in range(sizeW+sizeH-1)]

Cheers,
David Eccles (gringer)


More information about the Tutor mailing list