Description of challenge at the bottom.
The test case that keeps failing is matrixReshape( [[1,2],[3,4]] , 4, 1)
on line 22 "row[i] = queue.pop(0)", every row is changed instead of just the one being referenced.
So for every iteration the new_mat matrix ends up as [[3], [3], [3], [3]]; then [[4], [4], [4], [4]];
When it SHOULD be going [1, [2], [3], [None]]; then [1, [2], [3], [4]];
Someone else's python solution (which works somehow) is the same only they declared new_mat as:
[[None for _ in range(c)] for _ in range(r)]
instead of: [[None]*c]*r
I thought this was simply a data structure issue but when I printed out both versions of the matrices and their types, they were identical! Why doesn't mine work screenshot of code + submission
class Solution:
def matrixReshape(self, mat: List[List[int]], r: int, c: int) -> List[List[int]]:
if len(mat)*len(mat[0]) != r*c:
return mat
queue = []
for row in mat:
for col in row:
queue.append(col)
new_mat = [[None]*c]*r # <------ Is there an issue with how this is built?
for row in new_mat:
for i in range(c):
row[i] = queue.pop(0) # <----- Line 22
return new_mat
- Reshape the Matrix
In MATLAB, there is a handy function called reshape which can reshape an m x n matrix into a new one with a different size r x c keeping its original data.
You are given an m x n matrix mat and two integers r and c representing the number of rows and the number of columns of the wanted reshaped matrix.
The reshaped matrix should be filled with all the elements of the original matrix in the same row-traversing order as they were.
If the reshape operation with given parameters is possible and legal, output the new reshaped matrix; Otherwise, output the original matrix.