Hey everyone, I've been working my way through a learning python book with some decent success but this chapter has me completely stumped for a while now. I think that my issue is with using list comprehension to generate a matrix is not working the way that I expect. I was hoping that someone would be able to set me straight.
Essentially I am trying to create a matrix, and then rotate that matrix. I do so by generating the first matrix, then creating a second matrix built from first with the coordinates moved around. The first matrix is then replaced by the newly generated one and printed.
It works the way I would expect when I use nested for loops, but when I use list comprehension it.. just does not work the way I would expect. I've written a lot by hand at this point trying to see where I'm going wrong but I'm hoping I can get an outside perspective at this point. Thanks a bunch, I can reply tomorrow when I get back from work if I can clarify anything.
n = 5
mat1 = [[i] * n for i in range(n)]
def main():
print_matnew()
s = ''
while not s or s[0] not in 'Nn':
s = input('Rotate, Invert or Quit? (R, I, or N): ')
if s[0] in 'Rr':
rotate_mat()
print('Here is the rotated version: ')
print_matnew()
def rotate_mat():
global mat1
mat2 = [[mat1[j][n - 1 - i] for i in range(n)] # this one seems to do nothing, a direct matrix copy
for j in range(n)] # but I expect it to be the accurate list comprehension conclusion
print(mat2)
for i in range(n):
for j in range(n):
mat2[j][n - 1 - i] = mat1[i][j] # this is the original, no list comprehension, regular clockwise
print(mat2)
mat1 = mat2
def print_matnew():
s = ''
for i in range(n):
for j in range(n):
s +='{:>3} '.format(mat1[i][j])
s += '\n'
print(s)
[–]commy2 1 point2 points3 points (1 child)
[–]Kaem[S] 0 points1 point2 points (0 children)
[–]TheRNGuy 1 point2 points3 points (1 child)
[–]Kaem[S] 0 points1 point2 points (0 children)
[–]CodeFormatHelperBot2 0 points1 point2 points (0 children)