In: Computer Science
Write the following Python script:
Imagine you live in a world without modules in Python! No numpy! No scipy! Write a Python script that defines a function called mat_mult() that takes two lists of lists as parameters and, when possible, returns a list of lists representing the matrix product of the two inputs. Your function should make sure the lists are of the appropriate size first - if not, your program should print “Invalid sizes” and return None. Note: it is actually tricky to make a useful list of zeros. For instance, if you need to start with a 5 row, 6 column double list of 0, you might be tempted to try:
'''
thing = [ [ 0 ] ∗ 6 ] ∗ 5
'''
and if you look at it in the console window, it would appear to be a 5 by 6 list of lists containing all zeros! However - try the following and see what happens:
'''
thing [ 2 ] [ 5 ]
thing
'''
Notice that the item in index 5 of every row has changed, not just the row with index 2! Given the difficulty, I will give you the line of code that will create a list of lists that is num_rows by num_cols:
'''
ans = [ [ 0 for col in range ( num_cols ) ] for row in range ( num_rows ) ]
'''
def multiplyMatrix(A,row1, col1, B, row2, col2):
# Matrix to store the result
C = [[0 for i in range(MAX)] for j in range(MAX)]
# Checking if the multiplication is Possible or not
if (row2 != col1) :
print("Invalid Sizes")
return None
# Multiplying
for i in range(row1) :
for j in range(col2) :
C[i][j] = 0
for k in range(row2) :
C[i][j] += A[i][k] * B[k][j];
print("Resultant Matrix(AxB): ")
for i in range(row1) :
for j in range(col2) :
print(C[i][j], end = " ")
print()
MAX = 1000
A = [[0 for i in range(MAX)] for j in range(MAX)]
B = [[0 for i in range(MAX)] for j in range(MAX)]
row1 = int(input("Enter the number of rows of First Matrix: "))
col1 = int(input("Enter the number of columns of First Matrix: "))
print("Enter the elements of First Matrix: ");
for i in range(row1) :
for j in range(col1) :
A[i][j] = int(input())
row2 = int(input("Enter the number of rows of Second Matrix: "))
col2 = int(input("Enter the number of columns of Second Matrix: "))
print("Enter the elements of Second Matrix: ");
for i in range(row2) :
for j in range(col2) :
B[i][j] = int(input())
print("A: ")
for i in range(row1) :
for j in range(col1) :
print(A[i][j], end = " ")
print()
print("B: ")
for i in range(row2) :
for j in range(col2) :
print(B[i][j], end = " ")
print()
multiplyMatrix(A, row1, col1, B, row2, col2)