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 ) ]
'''
Hi,
As per your question, created the matrics of two lists of lists.
#------------------------------------------------------------
#do you need like this ?..means we will take input from user like first list legth 2*3 and second list leength of 3*5
list1_row= int(input("Please enter length of rows as integer value for list 1 > "))
list1_col = int(input("Please enter length of columns as integer value for list 1 > "))
list2_row = int(input("Please enter length of rows as integer value for list 2 > "))
list2_col= int(input("Please enter length of columns as integer value for list 2 > "))
if list1_col ==list2_col:
# creating list os lists or 2D list
list1 = ans = [ [ 0 for col in range ( list1_col ) ] for row in range ( list1_row ) ]
list2 = ans = [ [ 0 for col in range ( list2_col ) ] for row in range ( list2_row ) ]
# list of lists 1
print("1. list of lists->\n")
print(list1)
#list of lists 2
print("2. list of lists->\n")
print(list2)
#appending list2 elementsin list1
for rw in list2:
list1.append(rw)
#printing matrics of 2 lists of lists
print("2D matrics of two lists->\n")
print(list1)
#printing in matrics form
print("Matrics of two lists of lists\n")
for row in list1: print(*row)
else:
print("Please enter correct size of both lists..columns length must be same for both list to create matrics(2D array)")
Output: