ArJun Gawali
ArJun Gawali

Reputation: 47

Find product of all sublist's elemens of a list

We have a list lets take it

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

I want the result as multiplication of all sublist's elements
for example:

result = [1,2,3,4,5,2,6,24,120,6,24,120,12,60,20]

In minimum time possible

Explation of above result is there are subsets of lst which are :

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

I have tried it but its runtime is very much

N=[1,2,3,4]
X=[]
for i in range(len(N)+1):
    for j in range(len(N)+1):
        c=N[i:j]
        X.append(c)

print(X)
X2 = [x for x in X if x != []]
print(X2)

S=[]
for i in X2:
    p=1 
    for j in i:
        p=p*j 
    S.append(p)

print(S)

Upvotes: 0

Views: 498

Answers (3)

Eduardo Pascual Aseff
Eduardo Pascual Aseff

Reputation: 1166

If you use range(len(N)) and use N[i:j+1] you form all subarrays without empty arrays. In my solution X is not needed, but I left it there. With this code you have less multiplications, because you re-use results of previous subarrays multiplications:

N=[1,2,3,4,5,6,7,8,9,10]
#X=[]
S=[]
for i in range(len(N)):
    p=1
    for j in range(i, len(N)):
        p=p*N[j]
        #X.append(N[i:j+1])
        S.append(p)

#print(X)
print(S)

Upvotes: 1

nagataaaas
nagataaaas

Reputation: 420

As minimum as possible multiplication is better.

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


def all_product(nums: list):
    products = []
    numbers = len(nums)
    for i in range(numbers):
        products.append(nums[i])
        for j in range(i + 1, numbers):
            products.append(products[-1] * nums[j])
    return list(products)


print(sorted(all_product(nums)))
# [1, 2, 2, 3, 4, 5, 6, 6, 12, 20, 24, 24, 60, 120, 120]

print(sorted([1, 2, 3, 4, 5, 2, 6, 24, 120, 6, 24, 120, 12, 60, 20]))
# [1, 2, 2, 3, 4, 5, 6, 6, 12, 20, 24, 24, 60, 120, 120]

Upvotes: 1

Gilseung Ahn
Gilseung Ahn

Reputation: 2624

Use numpy.prod and itertools.combinations. Here is the code you want.

import itertools
import numpy as np
lst = [1,2,3,4,5]
result = []
for r in range(1, len(lst) + 1):
    for val in itertools.combinations(lst, r):
        result.append(np.prod(val))

the result is [1, 2, 3, 4, 5, 2, 3, 4, 5, 6, 8, 10, 12, 15, 20, 6, 8, 10, 12, 15, 20, 24, 30, 40, 60, 24, 30, 40, 60, 120, 120].

Upvotes: 1

Related Questions