Tuesday 12 May 2020

Reshape the Matrix | Python

Problem Statement:

In MATLAB, there is a very useful function called 'reshape', which can reshape a matrix into a new one with different size but keep its original data.

You're given a matrix represented by a two-dimensional array, and two positive integers r and c representing the row number and column number of the wanted reshaped matrix, respectively.

The reshaped matrix need to 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.

Example 1:
Input:
nums =
[[1,2],
 [3,4]]
r = 1, c = 4
Output:
[[1,2,3,4]]
Explanation:
The row-traversing of nums is [1,2,3,4]. The new reshaped matrix is a 1 * 4 matrix, fill it row by row by using the previous list.
Example 2:
Input:
nums =
[[1,2],
 [3,4]]
r = 2, c = 4
Output:
[[1,2],
 [3,4]]
Explanation:
There is no way to reshape a 2 * 2 matrix to a 2 * 4 matrix. So output the original matrix.
Note:
The height and width of the given matrix is in range [1, 100].
The given r and c are all positive.


Code:

class Solution:
    def matrixReshape(self, nums: List[List[int]], r: int, c: int) -> List[List[int]]:
        k=len(nums);
        m=len(nums[0]);
        if(k*m==r*c):
            l=[];
            for i in nums:
                l=l+i;
            i=0;
            j=0;
            output=[];
            k=[];
            temp=0;
            while(i<r):
                while(j<c):
                    k.append(l[temp]);
                    temp+=1;
                    j=j+1;
                output.append(k);
                k=[];
                j=0;
                i=i+1;
            return output;
        else:
            return nums;

0 Comments:

Post a Comment

Popular Posts

Categories

AI (27) Android (24) AngularJS (1) Assembly Language (2) aws (17) Azure (7) BI (10) book (4) Books (112) C (77) C# (12) C++ (82) Course (60) Coursera (176) coursewra (1) Cybersecurity (22) data management (11) Data Science (85) Data Strucures (6) Deep Learning (9) Django (6) Downloads (3) edx (2) Engineering (14) Excel (13) Factorial (1) Finance (5) flutter (1) FPL (17) Google (18) Hadoop (3) HTML&CSS (46) IBM (25) IoT (1) IS (25) Java (92) Leet Code (4) Machine Learning (43) Meta (18) MICHIGAN (4) microsoft (3) Pandas (3) PHP (20) Projects (29) Python (719) Python Coding Challenge (155) Questions (2) R (70) React (6) Scripting (1) security (3) Selenium Webdriver (2) Software (17) SQL (40) UX Research (1) web application (8)

Followers

Person climbing a staircase. Learn Data Science from Scratch: online program with 21 courses