0

To print matrix using python

you will be provided with the number of rows i.e. r and columns i.e. c as the input and your job is to create a matrix of size rxc. Also, the matrix should have elements starting from 1 to rxc with an increment of one in row manner. Example: if r = 2 and c = 3 then the output is 1 2 3 4 5 6 Input Format: Two numbers r and c in a single line separated by a space. Output Format: Elements of the generated matrix. Each row should be printed in a new line with each element separated by a space. Example: Input: 3 4 Output: 1 2 3 4 5 6 7 8 9 10 11 12 input: 3 1 output: 1 2 3

2nd Sep 2018, 10:54 AM
Krishnanshu Dey
Krishnanshu Dey - avatar
7 Answers
0
here is the solution r,c =input().split(" ") r=int(r) c=int(c) mat=[[0 for i in range(c)]for j in range(r)] val=1 for i in range(r): for j in range(c): mat[i][j]=val val=val+1 for i in range(r): for j in range(c): if j !=(c-1): print(mat[i][j],end=" ") else: print(mat[i][j],end="") if i!=(r-1): print()
4th Sep 2018, 7:31 AM
Krishnanshu Dey
Krishnanshu Dey - avatar
+ 1
def createMatrix(a,b): matrix, q = [], 0 for _ in range(a): auxrow = [] for _ in range(b): q += 1 auxrow.append(q) matrix.append(auxrow) return matrix This is done writing by rows, using an auxiliar row that its restarted when finishing each row. Then append it to final matrix. q is the integer number increase.
2nd Sep 2018, 11:51 AM
Seymour_ARM
Seymour_ARM - avatar
0
tnx for your ans. but it isn't working. showing no output
2nd Sep 2018, 1:15 PM
Krishnanshu Dey
Krishnanshu Dey - avatar
0
tnx for your ans. but it isn't working. showing no output
2nd Sep 2018, 1:16 PM
Krishnanshu Dey
Krishnanshu Dey - avatar
0
You have to call the function and give it some arguments to use it. Add "print(createMatrix(3,4))" at the end of the script. Dont put any indentation on this last statement, as it's not part of the function.
2nd Sep 2018, 2:18 PM
Seymour_ARM
Seymour_ARM - avatar
0
sorry it's didn't print the same pattern. It's printing as array. But I have to print that as pattern
3rd Sep 2018, 5:09 AM
Krishnanshu Dey
Krishnanshu Dey - avatar
0
Just write the code for i in range(row): print(mat[row]) Works for square matrix Here mat is a 2D matrix though
1st Nov 2018, 7:31 AM
Debkanti Das
Debkanti Das - avatar