I'm attempting to perform a 90 degree clockwise rotation of a 2D matrix like so:
Goal: Rotate CW
[1,2,3]
[4,5,6]
[7,8,9]
----Reverse order of rows in matrix.
[7,8,9]
[4,5,6]
[1,2,3]
----Zip together first elements in each row.
[7,4,1]
[8,5,2]
[9,6,3]
I wrote the following function to do this, which works fine when I run it on my own test data:
# Works on my own test cases
def rotate_matrix(square_matrix):
square_matrix = zip(*square_matrix[::-1])
square_matrix = list(map(list, square_matrix))
return square_matrix
For example:
m1 = [[1, 2],
[3, 4]]
r1 = rotate_matrix(m1)
# r1:
# [[3, 1]
# [4, 2]]
m2 = [[1,2,3,4],
[5,6,7,8],
[9,10,11,12],
[13,14,15,16]]
r2 = rotate_matrix(m2)
# r2:
# [[13, 9, 5, 1]
# [14, 10, 6, 2]
# [15, 11, 7, 3]
# [16, 12, 8, 4]]
Now, I'm following the book Elements of Programming Interviews in Python which has a test framework for these questions (located here https://github.com/adnanaziz/EPIJudge) , and I am unable to pass any test cases unless I modify my code to the following:
# Works on EPI test cases
def rotate_matrix(square_matrix):
square_matrix[:] = zip(*square_matrix[::-1])
square_matrix[:] = map(list, square_matrix)
return square_matrix
I thought I understood the idiosyncrasies of python lists, but I am at a loss here. I am trying to modify the list in place, so why is it necessary to use square_matrix[:]
rather than square_matrix
in the assignment statement?
Again its only when I run this within the EPI test framework that this is a problem. In fact, as soon as I delete the [:]
PyCharm tells me "Local variable 'square_matrix' value is not used".