Home > database >  Printed stdout shows that array has been modified, but output shows it has not been modified
Printed stdout shows that array has been modified, but output shows it has not been modified

Time:11-01

I am attempting to solve the LeetCode problem "Rotate Image" where a 2D int array is rotated clockwise 90 degrees(visual representation). I have found a working solution, however when I try to reassign the 2D integer array called "matrix", nothing is modified. I added a print statement that demonstrates in the stdout that at some point matrix is being modified, however the program output doesn't match the stdout. Even if I hardcode the correct answer (as I did in the commented out line), the output always matches the input.

Can anyone shed some light on what exactly is happening here?

code:

import numpy as np

    class Solution:
        def rotate(self, matrix: List[List[int]]) -> None:
            matrix = [np.asarray(col[::-1]) for col in zip(*matrix)]
            # matrix = [[7,4,1],[8,5,2],[9,6,3]]
            for col in matrix:
                print(col)

input:

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

stdout:

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

output:

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

expected:

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

CodePudding user response:

I think you'll have to post more code because the core of what you are trying to do is working:

import numpy as np

def rotate(matrix):
    matrix = [np.asarray(col[::-1]) for col in zip(*matrix)]
    # matrix = [[7,4,1],[8,5,2],[9,6,3]]
    print(matrix)

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

> rotate(matrix)
[array([7, 4, 1]), array([8, 5, 2]), array([9, 6, 3])]

CodePudding user response:

You are almost there. The np.asarray in your code is in the wrong place.

import numpy as np


def rotate(matrix):
    matrix = np.array([col[::-1] for col in zip(*matrix)])
    print(matrix)

Let's try rotating some matrices.

>>> rotate([[1, 2, 3],
...         [4, 5, 6],
...         [7, 8, 9]])
[[7 4 1]
 [8 5 2]
 [9 6 3]]

Rotating a four by four matrix.

>>> rotate([[ 1,  2,  3,  4],
...         [ 5,  6,  7,  8],
...         [ 9, 10, 11, 12],
...         [13, 14, 15, 16]])
[[13  9  5  1]
 [14 10  6  2]
 [15 11  7  3]
 [16 12  8  4]]

Also, I understand the reason why you think your code did not work.

When we loop through an array, we take rows from each iteration, instead of columns. So you should interpret it like this.

for row in matrix:
    print(row)

Instead of the following.

for col in matrix:
    print(col)
  • Related