Jingbo Liu
Jingbo Liu

Reputation: 13

Matrix Rotation Unexpected Result

I am a newbie for Python, and encountered a problem about matrix rotation. Following is my code

def rotateMatrix(matrix):
    if matrix == []:
        return []
    row, col = len(matrix), len(matrix[0])
    res = [[0]*row]*col
    for i in range(row):
        for j in range(col):
            res[col-1-j][i] = matrix[i][j]
    return res

mat = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
print rotateMatrix(mat)

The print result is [4,8,12] for all 4 rows!!! I just don't know where is the problem

Upvotes: 0

Views: 59

Answers (1)

Steven Summers
Steven Summers

Reputation: 5404

This issue is with

res = [[0]*row]*col

Because you are repeating a single list col times you get this behaviour.

>>> res = [[0]*3]*4
>>> res
[[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]
>>> res[0][0] = 1
>>> res
[[1, 0, 0], [1, 0, 0], [1, 0, 0], [1, 0, 0]]

Which is the same as this.

>>> x = []
>>> y = x
>>> x.append(5)
>>> x
[5]
>>> y
[5]

Instead you should use list comprehension if you want a one-liner.

res = [ [ 0 for r in range(rows) ] for c in range(col) ]

Or

res = [ [ 0 ] * rows for c in range(col) ]

Upvotes: 1

Related Questions