Product of everything except current in Python
from numpy import array
def product(input, index):
a = array(input)[index]
if a[a == 0].size != 1:
a = a.prod() / a # product except current
else:
# exaclty one non-zero-valued element in `a`
nzi = a.nonzero() # indices of non-zero-valued elements
a[a == 0] = a[nzi].prod()
a[nzi] = 0
return a
Example:
for input in ([2,3,4,5], [2,0,4,5], [0,3,0,5]):
print product(input, [1,3,2,0])
Output:
[40 24 30 60]
[40 0 0 0]
[0 0 0 0]