This is the problem I have. Given a list
xList = [9, 13, 10, 5, 3]
I would like to calculate for sum of each element multiplied by subsequent elements
sum([9*13, 9*10, 9*5 , 9*3]) +
sum([13*10, 13*5, 13*3]) +
sum([10*5, 10*3]) +
sum ([5*3])
in this case the answer is 608.
Is there a way to do this perhaps with itertools
or natively with numpy
?
Below is a function I came up with. It does the job but it is far from ideal as I would like to add other stuff as well.
def SumProduct(xList):
''' compute the sum of the product
of a list
e.g.
xList = [9, 13, 10, 5, 3]
the result will be
sum([9*13, 9*10, 9*5 , 9*3]) +
sum([13*10, 13*5, 13*3]) +
sum([10*5, 10*3]) +
sum ([5*3])
'''
xSum = 0
for xnr, x in enumerate(xList):
#print xnr, x
xList_1 = np.array(xList[xnr+1:])
#print x * xList_1
xSum = xSum + sum(x * xList_1)
return xSum
Any help appreciated.
N.B: In case you wonder, I am trying to implement Krippendorf's alpha with pandas
Here's one way:
In [14]: x = [9, 13, 10, 5, 3]
In [15]: np.triu(np.outer(x, x), k=1).sum()
Out[15]: 608
but I'd go with @user2357112's answer.