Created
August 25, 2019 23:55
-
-
Save stevenrouk/66c4f6271a15e4ee179a1a1d909795e5 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import numpy as np | |
| def list_comp_matrix_multiplication2(A, B): | |
| """Second version of the list comprehension matrix multiplication. | |
| In this version, we create a list comprehension out of our outer for loop. | |
| """ | |
| # The following line is no longer needed: | |
| # new_matrix = [] | |
| # The line comprehension is split across multiple lines for readability. | |
| # | |
| # Notice that the first, long line is just the list comprehension that we | |
| # currently have in the for loop. | |
| new_matrix = [ | |
| [sum([x*y for (x, y) in zip(row, col)]) for col in zip(*B)] | |
| for row in A | |
| ] | |
| # The following for loop is no longer needed. | |
| # for row in A: | |
| # new_row = [sum([x*y for (x, y) in zip(row, col)]) for col in zip(*B)] | |
| # | |
| # new_matrix.append(new_row) | |
| return new_matrix | |
| if __name__ == '__main__': | |
| A = [[1, 2, 3], [4, 5, 6]] | |
| B = [[7, 8], [9, 10], [11, 12]] | |
| print(for_loop_matrix_multiplication(A, B)) | |
| # The result should be: [[58, 64], [139, 154]] | |
| # You can check this by doing: np.matmul(A, B) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment