Since we are creating an array matrix, let me give you a brief of what exactly array is, Array is basically a collection of items of same data type. Each and every item that get stored in array is called element which are usually identified by its index.
To create matrix, I have defined a function create_integer_matrix(rows,cols,intgr), which takes three input parameters as below:
- Rows=Number of Rows
- Cols=Number of Columns
- Intgr=Integer Value
Here Rows & Cols are used to define number of rows and columns of a matrix and Intgr will define the starting number to print a sequence of numbers as per size of matrix.
for example: If my matrix is of size 3x3(Rows x Cols) and Ingr value is 1 then output will be :
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
Below is the function:
def create_integer_matrix(rows, cols, intgr):
matrix = []
for i in range(rows):
row = []
for j in range(cols):
row.append(intgr)
intgr = intgr + 1
matrix.append(row)
matrix = '\n'.join(str(r) for r in matrix)
return matrix
So in the above function a list matirx=[] is declared and a nested for loop is defined which loops based on input rows and columns. The outer loop will iterate as per number of rows and inner loop for range of columns.
After each iteration of inner loop the intgr value will get incremented by 1 and get appended to row=[] list variable, which further gets appended to matrix variable to form first row of matrix like "[1, 2, 3]"
Below is the full code:
def create_integer_matrix(rows, cols, intgr):
matrix = []
for i in range(rows):
row = []
for j in range(cols):
row.append(intgr)
intgr = intgr + 1
matrix.append(row)
matrix = '\n'.join(str(r) for r in matrix)
return matrix
#main function
def main():
rows=3 #Number of matrix row
cols=3 #Number of columns
intgr=1 # Start of integr series number
mtrx=create_integer_matrix(rows,cols,intgr)
print(mtrx)
if __name__ == '__main__':
main()
Hope that you find it helpful.
No comments:
Post a Comment