Multiplying Boolean Matrices

Viewed 894

I am trying to explicitly multiple 2 Boolean matrices, regardless of the number of rows or columns.

For example if A = [[0, 1, 1], [1, 0, 1]] and B = [[1, 0], [0, 0], [0, 1]], then the product is [[0, 1], [1, 1]].

Edit: I want to this explicitly without the numpy.

5 Answers

This answer works without numpy:

from itertools import starmap
from operator import mul
A = [[0, 1, 1], [1, 0, 1]]
B = [[1, 0], [0, 0], [0, 1]]
result = [[sum(starmap(mul, zip(row, col))) for col in zip(*B)] for row in A]
print(result)
>> [[0, 1], [1, 1]]

Install numpy (pip install numpy)

import numpy as np
a = np.matrix([[0,1,1],[1,0,1]], dtype=bool)
b = np.matrix([[1,0],[0,0],[0,1]], dtype=bool)
print(a*b)

This produces the result:

[[False True] [ True True]]

Which is the same as [[0,1],[1,1]]

You could first tranfer it to ndarray, and then multiply them.

import numpy as np


A = np.array( [[0, 1, 1], [1, 0, 1]], dtype=bool)
B = np.array([[1, 0], [0, 0], [0, 1]], dtype=bool)
result = np.dot(A, B)

print(result)

I found an answer without any unnecessary imports:

>>> A = [[0, 1, 1], [1, 0, 1]]
>>> B = [[1, 0], [0, 0], [0, 1]]
>>> [[sum(a*b for a,b in zip(X_row,Y_col)) for Y_col in zip(*B)] for X_row in A]
[[0, 1], [1, 1]]
>> np.matmul(A,B)

array([[0, 1],
       [1, 1]])
Related