A Product Array Puzzle | Function to print product array for a given array arr [ ] of size n ; Base case ; Allocate memory for the product array ; In this loop , temp variable contains product of elements on left side excluding arr [ i ] ; Initialize temp to 1 for product on right side ; In this loop , temp variable contains product of elements on right side excluding arr [ i ] ; Print the constructed prod array ; Driver Code
def productArray ( arr , n ) : NEW_LINE INDENT if n == 1 : NEW_LINE INDENT print ( 0 ) NEW_LINE return NEW_LINE DEDENT i , temp = 1 , 1 NEW_LINE prod = [ 1 for i in range ( n ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT prod [ i ] = temp NEW_LINE temp *= arr [ i ] NEW_LINE DEDENT temp = 1 NEW_LINE for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT prod [ i ] *= temp NEW_LINE temp *= arr [ i ] NEW_LINE DEDENT for i in range ( n ) : NEW_LINE INDENT print ( prod [ i ] , end = " ▁ " ) NEW_LINE DEDENT return NEW_LINE DEDENT arr = [ 10 , 3 , 5 , 6 , 2 ] NEW_LINE n = len ( arr ) NEW_LINE print ( " The ▁ product ▁ array ▁ is : ▁ n " ) NEW_LINE productArray ( arr , n ) NEW_LINE