How to create a matrix - def createMatrix(rows: int, cols: int) in python
I am 3 weeks old in my Python Journey. I came across this exercise where I need to create a 2D matrix using a function. The number of rows and columns of the matrix should be passed inside the function parameters on function call while the matrix elements should come from range() in respect to parameter values. Am trying to handle it like this:
def createMatrix(row, col):
mat = []
for in range(row):
mat.append([])
for in range(col):
|
This is what I was trying before I stuck there I stuck. Any help will be highly appreciated.
Solution 1:
Alternatively you could this List Comprehension
way:
def create_matrix(row, col):
''' create a 2D matrix by consecutive numbers - starting 1 - or change to whatever number in code
'''
matrix = [[ j + (col *i) for j in range(1, col+1)] # 1
for i in range(row)]
return matrix
print(create_matrix(4, 4))
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]
Solution 2:
this creates a 2d Matrix filled with 0:
def create_matrx(row, col):
grid = []
for row in range(col):
row = [0 for _ in range(col)]
grid.append(row)
return grid
creates a 2d Matrix with a given element
def create_matrx(row, col,element):
grid = []
for row in range(col):
row = [element for _ in range(col)]
grid.append(row)
return grid
creates a 2d Matrix filled with 0 to row+col
def create_matrx(row, col):
grid = []
for row in range(col):
row = [row+col for _ in range(col)]
grid.append(row)
return grid