What is the best way to test whether an array can be broadcast to a given shape?
The \"pythonic\" approach of try
ing doesn\'t work for my case, because the
To generalize this to arbitrarily many shapes, you can do so as follows:
def is_broadcast_compatible(*shapes):
if len(shapes) < 2:
return True
else:
for dim in zip(*[shape[::-1] for shape in shapes]):
if len(set(dim).union({1})) <= 2:
pass
else:
return False
return True
The corresponding test case is as follows:
import unittest
class TestBroadcastCompatibility(unittest.TestCase):
def check_true(self, *shapes):
self.assertTrue(is_broadcast_compatible(*shapes), msg=shapes)
def check_false(self, *shapes):
self.assertFalse(is_broadcast_compatible(*shapes), msg=shapes)
def test(self):
self.check_true((1, 2, 3), (1, 2, 3))
self.check_true((3, 1, 3), (3, 3, 3))
self.check_true((1,), (2,), (2,))
self.check_false((1, 2, 3), (1, 2, 2))
self.check_false((1, 2, 3), (1, 2, 3, 4))
self.check_false((1,), (2,), (3,))