1

I want to have two inputs : a,b or x,y whatever... When the user inputs say,

3 5

Then the shell should print a matrix with 3 rows and 5 columns also it should fill the matrix with natural numbers( number sequence starting with 1 and not 0). Example::

IN :2 2

OUT:[1,2] [3,4]

3 Answers 3

1

If your objective is only to get the output in that format

n,m=map(int,input().split())
count=0
for _ in range(0,n):
    list=[]
    while len(list) > 0 : list.pop()
    for i in range(count,count+m):
        list.append(i)
        count+=1
    print(list)
Sign up to request clarification or add additional context in comments.

3 Comments

This hits very close to what I want! Thank You Srinabh Sir!
What if I want to do it without brackets? like :: 1, 2/n 3,4
change the last print statement to print(*list)
0

I am going to give a try without using numpy library.

row= int(input("Enter number of rows"))
col= int(input("Enter number of columns"))
count= 1
final_matrix= []
for i in range(row):
    sub_matrix= []
    for j in range(col):
        sub_matrix.append(count)
        count += 1
    final_matrix.append(sub_matrix)

2 Comments

It says 'mat' is not defined.
I'm sorry there was a typo. I have edited the code. Hope this time it works. @ WISERDIVISOR
0

Numpy library provides reshape() function that does exactly what you're looking for.

from numpy import * #import numpy, you can install it with pip
    n = int(input("Enter number of rows: ")) #Ask for your input, edit this as desired.
    m = int(input("Enter number of columns: "))
    x = range(1, n*m+1) #You want the range to start from 1, so you pass that as first argument.
    x = reshape(x,(n,m)) #call reshape function from numpy
    print(x) #finally show it on screen

EDIT

If you don't want to use numpy as you pointed out in the comments, here's another way to solve the problem without any libraries.

n = int(input("Enter number of rows: ")) #Ask for your input, edit this as desired.
m = int(input("Enter number of columns: "))
x = 1 #You want the range to start from 1
list_of_lists = [] #create a lists to store your columns
for row in range(n):
    inner_list = []   #create the column
    for col in range(m):
        inner_list.append(x) #add the x element and increase its value
        x=x+1
    list_of_lists.append(inner_list) #add it

for internalList in list_of_lists: #this is just formatting.
    print(str(internalList)+"\n")

1 Comment

I edited the answer. The code without libraries is below it :) Hope it helps.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.