Home > Blockchain >  how to get a matrix from user then put it into a 2d list
how to get a matrix from user then put it into a 2d list

Time:02-05

I wonder how to get some information (obviously a matrix) from user and then put all those numbers into a 2D list? So I know there's probably prewritten function to do it, but I wanna make my own!

the Code down here and a description is my work that clearly doesn't work!!!!!

description: the program aquire user to enter a matrix in this form: a a a;a a a;a a a; which 'a' is an arbitrary number, and ';' points where a row ends! Almost like how we assign matrixes in matlab!

my code for the goal:

str = input("Enter a numerical squence: ")
print(len(str))
index_counter = 0
matrix = []
while index_counter < len(str) :
    rows = []
    while str[index_counter] != ";":
        if str[index_counter] == " ":
            index_counter  = 1
        else:
            rows.append(int(str[index_counter]))
            index_counter  = 1
    matrix.append(rows)   
print(matrix)

CodePudding user response:

Why are you using needless loops upon loops, just use split method which splits a string into list by delimiter?

Firstly split the entire string into 1d list by ';' then each list elements into sub lists by splitting using ' '

#getting input from user
inpt=str(input('enter matrix'))

#splitting string into 1D list of strings by ;
Matrix=inpt.split(';')[:-1]

#splitting substrings into sub list by ' '
for i in range(0,len(x)):
    Matrix[i]=Matrix[i].split(' ')

#display matrix
print(Matrix)

CodePudding user response:

Solution:

rows = int(input('number of rows: '))
cols = int(input('number of columns: '))

matrix = []

for i in range(0, rows):
    matrix.append([])
    for j in range(0, cols):
        matrix[i].append(input(':: '))
        
print (matrix)
  • Related