Nested List - Matrix and modules

# Creating modules for matrix manipulation 
# Matrix functions - Addition, Subtraction, Multiplication

# Matrix.py

# Matrix addition
def fnAdd(A,B):
# Check equal rows and columns
if((len(A) == len(B)) and (len(A[0])==len(B[0]))):
C=[]

for i in range(0,len(A)):
tmp=[]
for j in range(0,len(A[0])):
tmp.append(A[i][j]+B[i][j])
C.append(tmp)

print("Sum :")
print(C)

else:
print("Difference in order of matrix")
print("Cannot perform addition operation")


# Matrix subtraction 
def fnSub(A,B):
# Check equal rows and columns
if((len(A) == len(B)) and (len(A[0])==len(B[0]))):
C=[]

for i in range(0,len(A)):
tmp=[]
for j in range(0,len(A[0])):
tmp.append(A[i][j]-B[i][j])
C.append(tmp)
print("Difference :")
print(C)
else:
print("Difference in order of matrix")
print("Cannot perform subtraction operation")


# Matrix multiplication
def fnMul(A,B):
r1=len(A)
c1=len(A[0])
r2=len(B)
c2=len(B[0])

if(c1 == r2):
C=[]
for i in range(0,r1):
tmp=[]
for j in range(0,c2):
sum=0
for k in range(0,c1):
sum+=A[i][k]*B[k][j]
tmp.append(sum)
C.append(tmp)
print("Product :")
print(C)

else:
print("Difference in order of matrix")
print("Cannot perform Multiplication")
************************

# Matrix main program
# import the modules and call functions 

# Matrix program using module

import Matrix

A=[[1,2],[3,4]]
B=[[5,6],[3,4]]

Matrix.fnAdd(A,B)
Matrix.fnSub(A,B)
Matrix.fnMul(A,B)


"""
Sample output

>python Matrixmainpgm.py
Sum :
[[6, 8], [6, 8]]
Difference :
[[-4, -4], [0, 0]]
Product :
[[11, 14], [27, 34]]

"""


No comments:

Post a Comment

Don't be a silent reader...
Leave your comments...

Anu