Week - 5:
- Write a python program that defines a matrix and prints
Answer:
Method-1
// 2 x 3 matrix in Python
A = ( [ 2, 3, 6 ],
[ 4, 5, 8 ] )
# A basic code for matrix input from user
row = int(input("Enter the number of rows:"))
col= int(input("Enter the number of columns:"))
# Initialize matrix
matrix = []
print("Enter the entries row wise:")
# For user input
for i in range(row): # A for loop for row entries
a =[]
for j in range(col): # A for loop for column entries
a.append(int(input()))
matrix.append(a)
# For printing the matrix
for i in range(row):
for j in range(col):
print(matrix[i][j], end = " ")
print()
Output:
Enter the number of rows:2
Enter the number of columns:3
Enter the entries rowwise:
2
3
4
5
6
7
2 3 4
5 6 7
Explanation:
- This program is used to enter matrix elements dynamically and display them.
- row and col are variables used to determine the number of rows and columns of the matrix.
- matrix is a variable which stores matrix elements and matrix=[] is used to initialize empty matrix.
- i is a variable to run the loop for rows of the matrix.
- j is a variable to run the loop for columns of the matrix.
- a is an empty matrix variable.
- To enter the values dynamically we use input() function. The values entered will be taken in form of strings so we use int(input()) to convert string data type to integer data type.
- Each element of matrix entered will be added to the matrix by using append() function.
- Elements of matrix are displayed by using print function.
Method-2: Using map() function and Numpy.
import numpy as np
row = int(input("Enter the number of rows:"))
col = int(input("Enter the number of columns:"))
print("Enter the entries in a single line (separated by space): ")
# User input of entries in a
# single line separated by space
entries = list(map(int, input().split()))
# For printing the matrix
matrix = np.array(entries).reshape(row, col)
print(matrix)
Output:
Enter the number of rows:2
Enter the number of columns:3
Enter the entries in a single line (separated by space):
2 3 1 2 4 5
[[2 3 1]
[2 4 5]]
Explanation:
- This program generates as output as above by using Numpy library.
- np is the alternative name used to refer numpy.
- row and col are variables which are used to determine rows and columns of matrix.
- input() will read one line entered by the user.
- split() will split the line into words.
- (map(int, input().split())) will convert each word into integer.
- list(map(int, input().split())) will convert the elements into list elements.
- Variable entries is used to get the elements of the matrix.
- These elements are arranged in the form of rows and columns by using reshape(row, col)
- The arranged values are stored in matrix variable.
- The values are displayed using print() function.
- Write a python program to perform addition of two square matrices
Answer:
Let assume two matrices A and B, the task is to compute the sum of two matrices and then print it in Python.
Method-1: Using for loop:
A = [[1,4,3],
[4 ,5,6],
[7 ,6,9]]
B = [[9,5,7],
[6,8,4],
[3,2,1]]
result = [[0,0,0],
[0,0,0],
[0,0,0]]
# iterate through rows
for i in range(len(A)):
# iterate through columns
for j in range(len(A[0])):
result[i][j] = A[i][j] + B[i][j]
for r in result:
print(r)
Output:
[10, 9, 10]
[10, 13, 10]
[10, 8, 10]
Explanation:
- This program will perform addition of two matrices and display the result.
- A and B are two matrices which are assigned with values statically.
- result is the output matrix. Initially the result matrix is assigned with 0’s.
- len(A) will determine the length of the object matrix A.
- len(A(0)) will determine the length of the object matrix A[0](first row).
- i and j are variables that are used to run the loop to perform addition of two matrices.
- For each element r in result the values are displayed using print() function.
Method-2: Using nested list comprehension
Each row and each column have been iterated through using nested for loops. We add the matching elements from the two matrices at each position and output is stored.
In Python, we can apply a matrix as nested list (list inside a list). We can luxury every element as a row of the matrix.
A = [[1,2,3],
[4 ,4,6],
[7 ,5,9]]
B = [[4,8,7],
[6,5,4],
[5,2,1]]
result = [[A[i][j] + B[i][j]
for j in range(len(A[0]))]
for i in range(len(A))]
for r in result:
print(r)
Output:
[5, 10, 10]
[10, 9, 10]
[12, 7, 10]
Explanation:
- This program gives as same output as above program but using lists.
- The values of the matrix A and B are assigned statically.
- The addition of two matrices A and B are performed and is stored in result.
- len(A) will determine the length of the object matrix A.
- len(A(0)) will determine the length of the object matrix A[0](first row).
- i and j are variables that are used to run the loop to perform addition of two matrices.
- For each element r in result the values are displayed using print() function.
Method-3: Using numpy library
The numpy library has a built-in overload of the operator +, that allows one to perform the addition of matrices.
import numpy as np
A = [[1,4,3],
[4 ,5,6],
[7 ,5,9]]
B = [[9,7,7],
[6,4,4],
[3,2,1]]
result = np.array(A) + np.array(B)
print(result)
Output:
[[10 11 10]
[10 9 10]
[10 7 10]]
Explanation:
- This program performs same operation as above but using numpy library.
- np is an alternative name that can be used for numpy.
- A and B are matrices to which values are assigned statically.
- The values of the matrices A and B are added and the output is placed in result matrix.
- The values r of result are displayed using print() function.
- Write a python program to perform multiplication of two square matrices
Answer:
A = [[1,7,3],
[4 ,5,6],
[7 ,8,9]]
# 3x4 matrix
B = [[5,8,1,2],
[6,7,3,0],
[4,5,9,1]]
# result is 3x4
result = [[0,0,0,0],
[0,0,0,0],
[0,0,0,0]]
# iterate through rows of A
for i in range(len(A)):
# iterate through columns of B
for j in range(len(B[0])):
# iterate through rows of B
for k in range(len(B)):
result[i][j] += A[i][k] * B[k][j]
for r in result:
print(r)
Output:
[59, 72, 49, 5]
[74, 97, 73, 14]
[119, 157, 112, 23]
Explanation:
- This program will perform multiplication of two matrices and display the result.
- A and B are two matrices which are assigned with values statically.
- result is the output matrix. Initially the result matrix is assigned with 0’s.
- len(A) will determine the length of the object matrix A.
- len(B(0)) will determine the length of the object matrix B[0](first column).
- i,j and k are variables that are used to run the loop to perform multiplication of two matrices.
- For each element r in result matrix the elements are displayed using print() function.
Method-2: Nested list using zip().
A = [[2, 7, 3],
[4, 5, 6],
[7, 8, 9]]
# take a 3x4 matrix
B = [[5, 8, 1, 2],
[6, 7, 3, 0],
[4, 5, 9, 1]]
# result will be 3x4
result = [[sum(a * b for a, b in zip(A_row, B_col))
for B_col in zip(*B)]
for A_row in A]
for r in result:
print(r)
output:
[64, 80, 50, 7]
[74, 97, 73, 14]
[119, 157, 112, 23]
Explanation:
- This program gives as same output as above program but using lists.
- The values of the matrix A and B are assigned statically.
- The multiplication of two matrices A and B are performed and is stored in result.
- The zip() function will return a zip object, which is an iterator of tuples where the first item in each passed iterator is paired together, and then the second item in each passed iterator are paired together etc.
- For each element r in result the values are displayed using print() function.
Method-3: Using Numpy library (Vectorized implementation)
import numpy as np
# take a 3x3 matrix
A = [[2, 7, 3],
[4, 5, 6],
[7, 8, 9]]
# take a 3x4 matrix
B = [[5, 4, 1, 2],
[6, 7, 3, 0],
[4, 5, 9, 1]]
# result will be 3x4
result= [[0,0,0,0],
[0,0,0,0],
[0,0,0,0]]
result = np.dot(A,B)
for r in result:
print(r)
Output:
[64 72 50 7]
[74 81 73 14]
[119 129 112 23]
Explanation:
- This program performs same operation as above but using numpy library.
- np is an alternative name that can be used for numpy.
- A and B are matrices to which values are assigned statically.
- result matrix is used to store the output and display the values.
- To perform multiplication of two matrices we use dot(A,B). dot(A,B) is used to perform product of two arrays.
- The values r of result are displayed using print() function.
- How do you make a module? Give an example of construction of a module using different geometrical shapes and operations on them as its functions.
Answer:
What is module?
A module is a Python object that has attributes with arbitrary names and can be bound or referenced. A module is equivalent to an application package. A package is a group of modules organized into directories to provide order and structure.
Create modules in Python
Any Python file with the filename.py extension that can be imported into another Python programme is known as a module. The module name is changed to the name of the Python file. Classes, variables, and functions that can be utilized inside of another programme are defined and implemented in the module.
A module in Python is a standalone Python file that contains Python concepts and commands. For example, the file ABC.py can be viewed as an ABC module, which can be imported using the import command. However, the distinction among modules and packages could cause confusion.
- Use the structure of exception handling all general purpose exceptions.
Answer:
try:
numerator = 10
denominator = 0
result = numerator/denominator
print(result)
except:
print("Error: Denominator cannot be 0.")
Output:
ERROR!
Error: Denominator cannot be 0.
Explanation:
- This program will handle errors by using exception handling.
- This program uses static allocation.
- numerator and denominator are variables that holds some values.
- try block will contain the statements through which the error may occur.
- except block will contain the statements which handle the errors.
- result is a variable which contains the output.
- As result =numerator/denominator generate an divide by zero error the statements in except block will be executed and displayed.