Skip to content

Instantly share code, notes, and snippets.

@stevenrouk
Last active August 25, 2019 23:52
Show Gist options
  • Select an option

  • Save stevenrouk/f6ce591da65cce479117d3c94871d3fc to your computer and use it in GitHub Desktop.

Select an option

Save stevenrouk/f6ce591da65cce479117d3c94871d3fc to your computer and use it in GitHub Desktop.
import numpy as np
def list_comp_matrix_multiplication1(A, B):
"""First version of the list comprehension matrix multiplication.
In this version, we create a list comprehension out of our inner for loop.
"""
new_matrix = []
for row in A:
# This line is no longer needed:
# new_row = []
new_row = [sum([x*y for (x, y) in zip(row, col)]) for col in zip(*B)]
# The following for loop and append is no longer needed:
# for col in zip(*B):
# new_row.append(sum([x*y for (x, y) in zip(row, col)]))
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