keflavich keflavich - 4 months ago 12
Python Question

Test if an array is broadcastable to a shape?

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 intent is to have lazy evaluation of the operation.

I'm asking how to implement
is_broadcastable
below:

>>> x = np.ones([2,2,2])
>>> y = np.ones([2,2])
>>> is_broadcastable(x,y)
True
>>> y = np.ones([2,3])
>>> is_broadcastable(x,y)
False


or better yet:

>>> is_broadcastable(x.shape, y.shape)

Answer

I really think you guys are over thinking this, why not just keep it simple?

def is_broadcastable(shp1, shp2):
    for a, b in zip(shp1[::-1], shp2[::-1]):
        if a == 1 or b == 1 or a == b:
            pass
        else:
            return False
    return True