Program to find a list of product of all elements except the current index in Python


Suppose we have a list of numbers called nums, we have to find a new list such that each element at index i of the newly generated list is the product of all the numbers in the original list except the one at index i. Here we have to solve it without using division.

So, if the input is like nums = [2, 3, 4, 5, 6], then the output will be [360, 240, 180, 144, 120]

To solve this, we will follow these steps −

  • if size of nums < 1, then
    • return nums
  • l := size of nums
  • left := a list of size l and initially all values are null
  • right := a list of size l and initially all values are null
  • temp := 1
  • for i in range 0 to size of nums, do
    • if i is same as 0, then
      • left[i] := temp
    • otherwise,
      • temp := temp * nums[i - 1]
      • left[i] := temp
  • temp := 1
  • for i in range size of nums - 1 to 0, decrease by 1, do
    • if i is same as size of nums - 1, then
      • right[i] := temp
    • otherwise,
      • temp := temp * nums[i + 1]
      • right[i] := temp
  • for i in range 0 to size of nums, do
    • left[i] := left[i] * right[i]
  • return left

Let us see the following implementation to get better understanding −

Example

 Live Demo

class Solution:
   def solve(self, nums):
      if len(nums) < 1:
         return nums
      l = len(nums)
      left = [None] * l
      right = [None] * l
      temp = 1
      for i in range(len(nums)):
         if i == 0:
            left[i] = temp
         else:
            temp = temp * nums[i - 1]
            left[i] = temp
      temp = 1
      for i in range(len(nums) - 1, -1, -1):
         if i == len(nums) - 1:
            right[i] = temp
         else:
            temp = temp * nums[i + 1]
            right[i] = temp
      for i in range(len(nums)):
         left[i] = left[i] * right[i]
      return left
ob = Solution()
nums = [2, 3, 4, 5, 6]
print(ob.solve(nums))

Input

[2, 3, 4, 5, 6]

Output

[360, 240, 180, 144, 120]

Updated on: 19-Oct-2020

445 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements