keflavich - 9 months ago 41

Python Question

What is the best way to test whether an array can be broadcast to a given shape?

The "pythonic" approach of

`try`

I'm asking how to implement

`is_broadcastable`

`>>> 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
```