Forming each element of p
by direct multiplication of all but one of the elements of a
is wasteful ($O(n^2)$ in operations), so first we'll calculate the product of all the elements in a
and form p
by dividing this product by the appropriate element.
a = [1, 2, 3]
prod = 1
for e in a:
prod *= e
p = []
for e in a:
p.append(prod // e)
print(p)
If you are feeling scrupulous and want to cater for the presence of zeros in the list, a
(which would otherwise cause a ZeroDivisionError
exception to be raised), then the following code might be better for you:
a = [1, 2, 0, 3]
n = len(a)
nzeros = a.count(0)
if nzeros > 1:
p = [0] * n
else:
p = []
prod = 1
for e in a:
if e:
prod *= e
if nzeros == 1:
p = [0] * n
p[a.index(0)] = prod
else:
for e in a:
p.append(prod // e)
print(p)