Matrix input in python

Get matrix input from user in Python

A matrix is a rectangular arrangement of numbers arranged in rows and columns.

Eg :

3x3 matrix

        1  2  3
M =  4  5  6
        7  8  9

In python a matrix is nothing but a list of lists (sub list).
The above matrix can be written as [ [1,2,3], [4,5,6], [7,8,9] ].

Prerequisite : List in python

Method 1 :

In this method, we get the elements of matrix and append it to a list and append the entire list to a main list (matrix).

Code :

#function to print matrix

def printMatrix(matrix,r,c):

for i in range(r):

for j in range(c):

print(matrix[i][j],  end=" ")

print()


#Get the number of rows from user

r  = int(input("Enter the number of rows : "))

#Get the number of columns from the user

c  = int(input("Enter the number of columns : "))

#initialize a matrix(list)

matrix = []

for row in range(r):

l = []

for col in range(c):

                #Get elements one by one

num = int(input("Enter  element : "))

                #append the element to a list

l+=[num]

        #append the list to the matrix list

matrix+=[l]

#print matrix

printMatrix(matrix,r,c)

Output :

Matrix input in python
Method 1 - Output







Method 2 :

In this method we are using the map, list and split functions for getting the elements row wise. Here the user can enter the elements of a row separated by space.

Code :

#function to print matrix

def printMatrix(matrix):

for i in range(len(matrix)):

for j in range(len(matrix[i])):

print(matrix[i][j], end=" ")

print()


#Get the number of rows from user

n = int(input("Enter the number of rows : "))

#initialize a matrix(list)

matrix = []

for row in range(n):

        #Get the elements of a row separated by space and store in a list

l = list(map(int,input("Enter elements of row separated by space : ").split(" ")))

        #append the list to the matrix list

matrix+=[l]

#print the matrix

printMatrix(matrix)

Output :

Matrix input in python
Method 2 - Output






Method 3:

This method is a simplified version of method 1. Here we are using a

single line code to get the input.

Code :

#function to print matrix

def printMatrix(matrix,r,c):

for i in range(r):

for j in range(c):

print(matrix[i][j],  end=" ")

print()

#Get the number of rows from user

row = int(input("Enter the number of rows : "))

#Get the number of columns from user

col = int(input("Enter the number of columns : "))

#get the element and append it to the matrix

mat = [[int(input()) for c in range (col)] for r in range(row)]

#print matrix

printMatrix(mat,row,col)

Output :

Matrix input in python
Method 3 - Output


      


Comments

Popular posts from this blog

Finding the percentage in python - HackerRank solution

HackerRank challenges with solutions (Rearrangement, Formula, Word sorting, Numbers, Sentence)

ginortS in Python - HackerRank solution