Product of array except self Python program

This is program to solve product of array except self , present on leetcode.

This solution first appeared here.

The top solutions on leetcode use floor division even though the problem specifically says not to use division.

Hmm, it uses division hiding in power mask :)

Product of array except self python program


class Solution:
    def productExceptSelf(self, nums: List[int]) -> List[int]:
        """ 
        this one i wrote first 
        
        r = 1
        r_non_zero = 1
        zero_count = 0
        for n in nums:
            r *= n
            if n != 0 :
                r_non_zero = r_non_zero * n 
            else:
                zero_count += 1

        answers= [ r  for i in range (len(nums)) ]         
        for i in range(len(nums)) :  
            if nums[i] != 0 :
                answers[i] = int(answers[i]  * ( 1 *  ( nums[i] ** -1 )  ) )
            else:
                answers[i] = r_non_zero if zero_count == 1 else 0

        return answers
        """

        """ this one i learned """
        
        # readability can be improved by removing unncessary spaces , i am going to keep it :)
        answers = [ 1 ] * len(nums)

        prefix = 1
        for i in range(len(nums)):

            answers[i] = prefix
            
            prefix = prefix * nums[i]



Output:



Comments