2

I am starting to code in python. When I was to take two inputs from user with a space between the two inputs my code was like

 min, p = input().split(" ") 
min=int(min)
p=float(p)

which worked fine. In another such problem I am to take a n*n matrix as user input which I declared as arr=[[0 for i in range(n)] for j in range(n)] printing the arr gives a fine matrix(in a single row though) but I am to replace each element '0'with a user input so I use nested loops as

for i in range(0,n)
 for j in range(0,n)
 arr[i][j]=input()

this also worked fine but with a press of 'enter' button after each element. In this particular problem the user will input elements in one row at space instead of pressing 'enter' button. I wanted to know how to use split in this case like in first case above, keeping in mind the matrix is n*n where we don't know what is n. I prefer to avoid using numpy being a beginner with python.

jchanger
74810 silver badges29 bronze badges
asked Sep 8, 2015 at 20:02
1
  • What stops you from reading an input line, splitting her to a list, checking number of elements and possible conversion to numbers and copying them to your matrix as one row? Commented Sep 8, 2015 at 20:12

10 Answers 10

3

You can do this:

rows = int(input("Enter number of rows in the matrix: "))
columns = int(input("Enter number of columns in the matrix: "))
matrix = []
print("Enter the %s x %s matrix: "% (rows, columns))
for i in range(rows):
 matrix.append(list(map(int, input().rstrip().split())))

Now you input in the console values like this:

Enter number of rows in the matrix: 2
Enter number of columns in the matrix: 2
Enter the 2 x 2 matrix:
1 2
3 4
answered Jun 5, 2018 at 12:23
Sign up to request clarification or add additional context in comments.

Comments

3
#Take matrix size as input
n=int(input("Enter the matrix size"))
import numpy as np
#initialise nxn matrix with zeroes
mat=np.zeros((n,n))
#input each row at a time,with each element separated by a space
for i in range(n):
 mat[i]=input().split(" ")
print(mat) 
answered Sep 12, 2018 at 17:06

Comments

1

You can try this simple approach (press enter after each digit...works fine)::

m1=[[0,0,0],[0,0,0],[0,0,0]]
for x in range (0,3):
 for y in range (0,3):
 m1[x][y]=input()
print (m1)
answered Mar 20, 2017 at 12:20

3 Comments

and if you want to enter 1000*1000 matrix what should you do ?
just change the values in range (for loops) for both 'row for loop' and 'column for loop': "for x in range (0,1000)" and "for y in range (0,1000)"
so describe it in your answer
0

Try something like this instead of setting the matrix one by one using existing list(s):

# take input from user in one row
nn_matrix = raw_input().split()
total_cells = len(nn_matrix)
# calculate 'n'
row_cells = int(total_cells**0.5)
# calculate rows
matrix = [nn_matrix[i:i+row_cells] for i in xrange(0, total_cells, row_cells)]

Example:

>>> nn_matrix = raw_input().split()
1 2 3 4 5 6 7 8 9
>>> total_cells = len(nn_matrix)
>>> row_cells = int(total_cells**0.5)
>>> matrix = [nn_matrix[i:i+row_cells] for i in xrange(0, total_cells, row_cells)]
>>> matrix
[['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']]
>>> 
answered Sep 8, 2015 at 20:13

Comments

0
>>> import math
>>> line = ' '.join(map(str, range(4*4))) # Take input from user
'0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15'
>>> items = map(int, line.split()) # convert str to int
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
>>> n = int(math.sqrt(len(items))) # len(items) should be n**2
4
>>> matrix = [ items[i*n:(i+1)*n] for i in range(n) ]
[[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14, 15]]
answered Sep 8, 2015 at 20:20

Comments

0

Well if matrix is n*n that means with first input line you know number of input lines (and no, it's impossible for input() to not end with key enter is pressed). So you need something like this:

arr = []
arr.append(input().split())
for x in range(len(arr[0]) - 1):
 arr.append(input().split())

I used range(len(arr[0]) - 1) so it inputs rest of lines (because matrix width and height is same and one first line is already read from input).

Also I used .split() without " " as parameter because it's default parameter.

answered Sep 8, 2015 at 20:43

Comments

0

Try with below,

r=int(input("enter number of rows"));
c=int(input("enter number of columns"));
mat=[];
for row in range(r):
 a=[]
 for col in range(c):
 a.append(row*col);
 mat.append(a)
print mat;
Abhishek Gurjar
7,47610 gold badges41 silver badges47 bronze badges
answered Jun 18, 2019 at 4:01

Comments

0
print("Enter The row and column :")
row,col=map(int,input().split())
matrix = [] 
print("Enter the entries rowwise:") 
# For user input 
for i in range(row): # for loop for row entries 
a =[] 
for j in range(col): # for loop for column entries 
 a.append(int(input())) 
matrix.append(a) 
for i in range(row): 
 for j in range(col): 
 print(matrix[i][j], end = " ") 
print()
answered Jul 19, 2019 at 10:52

3 Comments

Code not intended
You can copy and paste this as it is ,then it will run
a =[] is not intended
0

n= 10 # n is the order of the matrix

matrix = [[int(j) for j in input().split()] for i in range(n)]

print(matrix)

answered Oct 26, 2019 at 8:25

Comments

0
r = int(input("Enret Number of Raws : "))
c = int(input("Enter Number of Cols : "))
a=[]
for i in range(r):
 b=[]
 for j in range(c):
 j=int(input("Enter Number in pocket ["+str(i)+"]["+str(j)+"]"))
 b.append(j)
 a.append(b)
for i in range(r):
 for j in range(c):
 print(a[i][j],end=" ")
 print()
Piotr Labunski
1,6564 gold badges21 silver badges27 bronze badges
answered Apr 27, 2020 at 10:39

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.