A Product Array Puzzle | Set 3 | Python 3 program for the above approach ; Function to form product array with O ( n ) time and O ( 1 ) space ; Stores the product of array ; Stores the count of zeros ; Traverse the array ; If arr [ i ] is not zero ; If arr [ i ] is zero then increment count of z by 1 ; Stores the absolute value of the product ; If Z is equal to 1 ; If arr [ i ] is not zero ; Else ; If count of 0 s at least 2 ; Assign arr [ i ] = 0 ; Store absolute value of arr [ i ] ; Find the value of a / b ; If arr [ i ] and product both are less than zero ; If arr [ i ] and product both are greater than zero ; Else ; Traverse the array arr [ ] ; Driver Code ; Function Call
import math NEW_LINE def productExceptSelf ( arr , N ) : NEW_LINE INDENT product = 1 NEW_LINE z = 0 NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( arr [ i ] != 0 ) : NEW_LINE INDENT product *= arr [ i ] NEW_LINE DEDENT if ( arr [ i ] == 0 ) : NEW_LINE INDENT z += 1 NEW_LINE DEDENT DEDENT a = abs ( product ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT if ( z == 1 ) : NEW_LINE INDENT if ( arr [ i ] != 0 ) : NEW_LINE INDENT arr [ i ] = 0 NEW_LINE DEDENT else : NEW_LINE INDENT arr [ i ] = product NEW_LINE DEDENT continue NEW_LINE DEDENT elif ( z > 1 ) : NEW_LINE INDENT arr [ i ] = 0 NEW_LINE continue NEW_LINE DEDENT b = abs ( arr [ i ] ) NEW_LINE curr = round ( math . exp ( math . log ( a ) - math . log ( b ) ) ) NEW_LINE if ( arr [ i ] < 0 and product < 0 ) : NEW_LINE INDENT arr [ i ] = curr NEW_LINE DEDENT elif ( arr [ i ] > 0 and product > 0 ) : NEW_LINE INDENT arr [ i ] = curr NEW_LINE DEDENT else : NEW_LINE INDENT arr [ i ] = - 1 * curr NEW_LINE DEDENT DEDENT for i in range ( N ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT arr = [ 10 , 3 , 5 , 6 , 2 ] NEW_LINE N = len ( arr ) NEW_LINE productExceptSelf ( arr , N ) NEW_LINE