Calculate all products for all numbers in a python list

Say I have this list:

[2,3,5,7] 

I want to deduce all combinations of multiplication:

[6,10,14,15,21,35,30,42,105,210]

Is there one liner for this in python?

+4
source share
3 answers

Assuming you forgot 70 in your exit ...

C numpy.prodand itertools.combinations:

>>> from numpy import prod
>>> from itertools import combinations
>>> lst = [2,3,5,7]
>>> [prod(x) for i in range(2, len(lst)+1) for x in combinations(lst, i)]
[6, 10, 14, 15, 21, 35, 30, 42, 70, 105, 210]
+7
source

Itertools is a good way. As an alternative solution, pure numpy is used (all products 0,1, ..., n terms):

from numpy import *
a,n=array(l),len(l)
where(bitwise_and.outer(arange(2**n),2**arange(n))>0,a,1).prod(1)
#array([  1,   2,   3,   6,   5,  10,  15,  30,   7,  14,  21,  42,  35, 70, 105, 210])

up to 40 times faster on large lists.

Some explanation:

bitwise_and.outer(arange(2**n),2**arange(n)) is an

array([[0, 0, 0, 0],
       [1, 0, 0, 0],
       [0, 2, 0, 0],
       [1, 2, 0, 0],
       [0, 0, 4, 0],
       [1, 0, 4, 0],
       [0, 2, 4, 0],
       [1, 2, 4, 0],
       [0, 0, 0, 8],
       [1, 0, 0, 8],
       [0, 2, 0, 8],
       [1, 2, 0, 8],
       [0, 0, 4, 8],
       [1, 0, 4, 8],
       [0, 2, 4, 8],
       [1, 2, 4, 8]], dtype=int32)

where(bitwise_and.outer(arange(2**n),2**arange(n))>0,a,1) is an

array([[1, 1, 1, 1],
       [2, 1, 1, 1],
       [1, 3, 1, 1],
       [2, 3, 1, 1],
       [1, 1, 5, 1],
       [2, 1, 5, 1],
       [1, 3, 5, 1],
       [2, 3, 5, 1],
       [1, 1, 1, 7],
       [2, 1, 1, 7],
       [1, 3, 1, 7],
       [2, 3, 1, 7],
       [1, 1, 5, 7],
       [2, 1, 5, 7],
       [1, 3, 5, 7],
       [2, 3, 5, 7]])

Then prodalong the line.

+2
source

...

, l:

[ list(l[k] for k in range(len(l))
    if (2**k) & (n+(n+n.bit_length()).bit_length()))
    for n in range(1,2**len(l)-len(l)) ]

( reduce , ). "" n+(n+n.bit_length()).bit_length(), , ( ), , , . http://oeis.org/A057716 ( Python "" ).

, :

[ reduce(int.__mul__,
    (l[k] for k in range(len(l))
        if (2**k) & (n+(n+n.bit_length()).bit_length())))
        for n in range(1,2**len(l)-len(l)) ]

( reduce, Python 3.)

0

Source: https://habr.com/ru/post/1624612/


All Articles