Algo Puzzle - Product of Elements of an ArrayI came across this interesting problem of coming up with an algorithm that would compute, for each element of an array, the product of all other elements in that array, in linear time without using the division operator (or implementing a division algorithm.) A solution is to traverse left to right computing the growing product, and then traverse right to left computing the growing product and multiplying it with the result from the previous traversal. I.e., Given,P Q R SCompute, 1 P PQ PQR x x x x QRS RS S 1 ------------------- QRS PRS PQS PQR Implemented in python,
def elProd( A ):
result = []
prod = 1
# for i from 0 up to len(A) - 1
for i in range( len( A ) ):
result.append( prod )
prod = prod * A[ i ]
prod = 1
# for i from len(A) - 1 down to 0
for i in range( len( A ) - 1, -1, -1 ):
result[ i ] = result[ i ] * prod
prod = prod * A[ i ]
return result
|
TopicsRecent blog posts
|