P2.4.1Product of all but one integers in a list
Write a short Python program which, given an list of integers, a, calculates a list of the same length, p, in which p[i] is the product of all the integers in a except a[i]. So, for example, if a = [1,2,3], then p is [6, 3, 2].
Show solution
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)