incorrect output when trying to rotate a matrix in python -
i'm trying rotate matrix(2-d list) in python 90 degrees clockwise. here code:
def rotate(matrix): length = len(matrix) new_matrix = [[0]*length]*length in range(length): j in range(length): new_matrix[j][length-1-i] = matrix[i][j] print("new_matrix[",j,"][", length-1-i,"]", "is", new_matrix[j][length-1-i]) in range(length): j in range(length): print(new_matrix[i][j]) return new_matrix print(rotate([[1 ,2], [3, 4]]))
the idea simple, after rotating, element i, j row number , column number have j, length-1-i row , column numbers.
the print statement used verify doing right. tried [[1, 2], [3, 4]] , got wrong answer , quite confusing output:
new_matrix[ 0 ][ 1 ] 1 new_matrix[ 1 ][ 1 ] 2 new_matrix[ 0 ][ 0 ] 3 new_matrix[ 1 ][ 0 ] 4 4 2 4 2 [[4, 2], [4, 2]]
it seems somehow values 1 , 3 got overwritten somehow. , when tried [[1, 2, 3], [4, 5, 6], [7, 8, 8]] , new_matrix became [[9, 6, 3], [9, 6, 3], [9, 6, 3]]
. there wrong here.
any idea why?
the problem in code line,
new_matrix = [[0]*length]*length
it's not doing think - creating list of length
number of same inner list.
replace following create distinct inner lists,
new_matrix = [[0]*length _ in range(length)]
Comments
Post a Comment