The question asks to rotate an image/matrix by 90 degrees. Ideally it asks to do it in place but before that I decided to do it using extra space because this is my first time working with matrices.
question: while using extra space, could this have been any better?
def rotate_m1(matrix, d): """ with extra space for each row in the orginal matrix, the items position in that row will be its row in the new matrix. Its position in the new row will be determined by 'l' (matrix row length), which decrements after each loop. e.g. 1,2 3,4 the loop goes through and maps the top row to the outside of a new matrix. i.e. i = 0 # row j = 0 # col // its postion in the row l = d-1 # d = the dimensions of the matrix matrix[i][j] = 1 in the new matrix the postion of matrix[i][j] (1) will be: new_matrix[j][l]; j being its postion in its original row, so in this case 1 was in postion 0 in the original matrix, and l is the outermost row of the new matrix becuse (in this example) during the first loop l = 2-1. after the first row is mapped, we take one away from l to map the next row to the row before the outer most row in the new matrix (d-2) """ m2 = [[0 for x in range(d)] for y in range(d)] # construct new matrix l = d-1 for i in range(len(matrix)): for j in range(len(matrix[i])): m2[j][l] = matrix[i][j] l -= 1 print m2
input: [[1,2,3], [4,5,6], [7,8,9]] output: [[7, 4, 1], [8, 5, 2], [9, 6, 3]]
I've added some extra info about how I came to the solution in the code comment.