Matrix input in python
Get matrix input from user in Python
#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 :
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 :
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)
Comments
Post a Comment