Home > Net >  Trying to rotate a matrix 90 degrees but fails to work
Trying to rotate a matrix 90 degrees but fails to work

Time:10-04

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

CodePudding user response:

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]]

CodePudding user response:

Here's a simply way with numpy:

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

rotated_90 = matrix.T[::-1]

CodePudding user response:

Instead of temporary.clear(), use temporary = [] to reset it in this case.

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

At putin.insert(putin_idx, temporary), you insert the list object you have been building into putin. Note that the list putin refers to this object, which is shared with temporary.

Then you invoke temporary.clear(). Now temporary refers to the list object, so python walks to this very object and clears it. This makes the list object (just inserted in putin) an empty list.

Using temporary = [] will sever the reference and let temporary refer a new empty list.

  • Related