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 ) ]
'''
Thanks for the question. Below is the code you will be needing. Let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please leave a +ve feedback : ) Let me know for any help with any other questions. Thank You! =========================================================================== def mat_mult(m1, m2): if len(m1) == 0 or len(m2) == 0: print('Invalid sizes') return None if len(m1[0]) != len(m2): print('Invalid sizes') return None num_rows, num_cols = len(m1), len(m2[0]) result = [[0 for col in range(num_cols)] for row in range(num_rows)] # iterate through rows of m1 for i in range(len(m1)): # iterate through columns of m2 for j in range(len(m2[0])): # iterate through rows of m2 for k in range(len(m2)): result[i][j] += m1[i][k] * m2[k][j] return result X = [[1,2,1],[1,2,3],[4,5,6]] Y = [[1,1,1],[2,2,2]] print(mat_mult(X,Y))
==========================================================================