How to compute sum of all the combinations of given list of numbers? -
suppose have list of numbers - a1,a2,a3,a4,a5,....,an.
how can compute - (a1*a2)+(a1*a3)+(a1*a4)+(a1*a5)+(a1*a6)+....
?
ex-for 1,2,3 ,i need calculate 1*2+2*3+1*3=11
.
also generalize solution combinations containing more 2 terms ex 3 terms-(a1*a2*a3)+(a1*a3*a4)+(a1*a4*a5)+(a2*a3*a4)+....
import itertools def sumofcombinations(l,s): return sum(prod(seq) seq in (itertools.combinations(l, s))) def prod(l): product = 1 x in l: product*=x return product #exemple mylist = [1,2,3] size = 2 print(sumofcombinations(mylist,size))
this job in python. there more pythonic ways accomplish this. results there.
Comments
Post a Comment