reshape_matrix

Write a Python function that reshapes a given matrix into a specified shape. if it cant be reshaped return back an empty list [ ]

np.array()

Introduce np.array()

difference between list in python and np.array()

NumPy’s arrays are more compact than Python lists – a list of lists as you describe, in Python, would take at least 20 MB or so, while a NumPy 3D array with single-precision floats in the cells would fit in 4 MB. Access in reading and writing items is also faster with NumPy.

NumPy is not just more efficient; it is also more convenient. You get a lot of vector and matrix operations for free, which sometimes allow one to avoid unnecessary work. And they are also efficiently implemented.

for example np.reshape()

Solution

transform to np_array and use np.reshape() and translate back

def reshape_matrix(a: list[list[int|float]], new_shape: tuple[int, int]) -> list[list[int|float]]:  
    #Write your code here and return a python list after reshaping by using numpy's tolist() method  
    numpy_array = np.array(a)  
    try:  
       reshape_matrix = numpy_array.reshape(new_shape).tolist()  
    except ValueError:  
       reshape_matrix = []  
    return reshape_matrix

Last modified April 8, 2025: update deepml (07975af)