0

I am trying to solve the following exercise:

Given an integer array nums, return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i].

Example 1:

Input: nums = [1,2,3,4]
Output: [24,12,8,6]

Example 2:

Input: nums = [-1,1,0,-3,3]
Output: [0,0,9,0,0]

Here is my code:

def inputArray():
    # creating an empty list
    lst = []
    
    # number of elements as input
    n = int(input("Enter number of elements : "))
    
    # iterating till the range
    for i in range(0, n):
        ele = int(input())
    
        lst.append(ele) # adding the element
        
    print(lst)
    return lst

l=inputArray()
array=[]
m=1
mul=1
for i in l:
    m*=i
    mul=m/i
for j in range(0,len(l)-1):
    array[j]=mul
    mul=1
print(array)

And I have the following eror: list assignment index out of range. I hope anyone could help me...

5
  • 1
    can you fix your code indentation please ? Commented Aug 31, 2022 at 17:33
  • You can't assign to array[j] to create a new element. Use array.append(mul) Commented Aug 31, 2022 at 17:34
  • I believe this is infamous Leetcode prodcutExceptItself prob. Req. is time O(n), space O(1) - that's why made it harder...than it should be. ;-) Commented Aug 31, 2022 at 17:38
  • It also states "and without using the division operation". The O(1) space req is just extra credit. Commented Aug 31, 2022 at 17:47
  • leetcode.com/problems/product-of-array-except-self ??? Given an integer array nums, return an array answer such that answer[i] is equal to the product of all the elements of nums except nums[i]. The product of any prefix or suffix of nums is guaranteed to fit in a 32-bit integer. You must write an algorithm that runs in O(n) time and without using the division operation. Commented Aug 31, 2022 at 17:49

2 Answers 2

1

You're setting array[j]=mul but you never added any items to array so there's nothing to index. You have to either pre-fill the array or just append items to it instead.

Sign up to request clarification or add additional context in comments.

Comments

1

As array is empty, you cannot access it using indexing, but you don't need that, just append the product divided by the current value

l = [1, 2, 3, 4]
result = []
m = 1

for value in l:
    m *= value
for value in l:
    result.append(m / value)

print(result)  # [24.0, 12.0, 8.0, 6.0]

That solution works only if 0 is not the list, if it is, you need more calcultation as you need to compute the product for each position

result = []
for idx, value in enumerate(l):
    m = 1
    for jdx, value in enumerate(l):
        if idx != jdx:
            m *= value
    result.append(m)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.