Trying to rotate a matrix 90 degrees but fails to work

Viewed 68
def rotate_ninety(matrix):
    putin = []
    temporary = []
    row_size = len(matrix)
    col_size = len(matrix[0])
    ccount = col_size-1
    putin_idx = 0
    while ccount > -1:
        for i in range(row_size):
            temporary.insert(i, matrix[i][ccount])

        putin.insert(putin_idx, temporary)
        ccount = ccount -1
        temporary.clear()
        putin_idx += 1

    print(putin)
    return 0

So, if I had the input

[1,2,3]
[4,5,6]
[7,8,9]

The result should be:

[3,6,9]
[2,5,8]
[1,4,7]

However, when I print putin I get [[] [] []], an array of all empty things, which I don't understand where my logic went wrong. I know there are other more efficient ways to do this, but I don't see how my code is wrong

2 Answers

When you assign (append or insert) a list to a variable (another list), the list object will be assigned or appended. Since after you add the temporary list to the putin list and then clearing the temporary, the object that has been added just got removed ,too. You need to add a copy of the temporary list to the putin, like this:

import copy

def rotate_ninety(matrix):
    putin = []
    temporary = []
    row_size = len(matrix)
    col_size = len(matrix[0])
    ccount = col_size-1
    putin_idx = 0
    while ccount > -1:
        for i in range(row_size):
            temporary.append(matrix[i][ccount])
        putin.append(copy.copy(temporary))
        ccount = ccount -1
        temporary.clear()
        putin_idx += 1

    print(putin)
    return 0

matrix = [[1,2,3],[4,5,6],[7,8,9]]
rotate_ninety(matrix)

And the result will be:
[[3, 6, 9], [2, 5, 8], [1, 4, 7]]

Here's a simply way with numpy:

matrix = np.arange(1,10).reshape((3,3))

rotated_90 = matrix.T[::-1]
Related