How can we take out the product of elements?

Viewed 96

I have the list named as input_list = [1, 2, 3, 4, 5] , I want to take the product of every elements except the specific index which is running at the moment.

Example

input_list1 = [1, 2, 3, 4, 5]

If I say that in the first index the value is 1 , in the output list, its product will be the all elements except first index (5*4*3*2) and insert it into new list, same goes for all elements.

Expected_Output:

prod = [120, 60, 40, 30, 24]
3 Answers

You can use math.prod for the task:

import math

out = [
    math.prod(input_list1[:i] + input_list1[i + 1 :])
    for i in range(len(input_list1))
]
print(out)

Prints:

[120, 60, 40, 30, 24]

Let's find the product of all the numbers in the list first.

from functools import reduce
from operator import mul


l = [1, 2, 3, 4, 5]
product = reduce(mul, l, 1)

Once we have it, let's iterate over all items in the list and divide the product by that item. This will give us the product of all the items except that one.

ans = [product // num for num in l]

Time Complexity: O(n)

This should work:

Code:

import math

input_list1 = [1, 2, 3, 4, 5]

def main(l):
    final = []
    for i in l:
        b = lambda a: int(a) if a == int(a) else a
        final.append(b(math.prod(input_list1) / int(i)))
    return final

prod = main(input_list1)
print(prod)

Output:

[120, 60, 40, 30, 24]

This should work.

Related