列表中对的乘积之和

时间:2015-05-04 20:25:45

标签: python numpy pandas itertools

这是我遇到的问题。给出一个列表

xList = [9, 13, 10, 5, 3]

我想计算每个元素的总和乘以后续元素

sum([9*13, 9*10, 9*5 , 9*3]) + 
sum([13*10, 13*5, 13*3]) + 
sum([10*5, 10*3]) + 
sum ([5*3])

在这种情况下答案是 608

是否可以使用itertools或本地使用numpy执行此操作?

以下是我提出的功能。它完成了这项工作,但它远非理想,因为我想添加其他东西。

    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

任何帮助表示赞赏。

N.B:如果您想知道,我正在尝试使用 pandas

来实施Krippendorf's alpha

6 个答案:

答案 0 :(得分:25)

x = array([9, 13, 10, 5, 3])
result = (x.sum()**2 - x.dot(x)) / 2

与其他可能具有二次性能的解决方案相比,这利用了一些数学简化来在线性时间和恒定空间中工作。

这是一个如何工作的图表。假设x = array([2, 3, 1])。然后,如果您将产品视为矩形区域:

x is this stick: -- --- -

x.sum()**2 is this rectangle:
   -- --- -
  |xx xxx x
  |xx xxx x

  |xx xxx x
  |xx xxx x
  |xx xxx x

  |xx xxx x

x.dot(x) is this diagonal bit:
   -- --- -
  |xx
  |xx

  |   xxx
  |   xxx
  |   xxx

  |       x

(x.sum()**2 - x.dot(x)) is the non-diagonal parts:
   -- --- -
  |   xxx x
  |   xxx x

  |xx     x
  |xx     x
  |xx     x

  |xx xxx

and (x.sum()**2 - x.dot(x)) / 2 is the product you want:
   -- --- -
  |   xxx x
  |   xxx x

  |       x
  |       x
  |       x

  |

答案 1 :(得分:7)

你真的想要组合而不是产品:

from itertools import combinations

print(sum(a*b for a,b in combinations(xList,2)))
608

即使从python列表创建一个numpy数组,@user2357112回答也会与我们其他人擦肩而过。

In [38]: timeit sum(a*b for a,b in combinations(xlist,2))
10000 loops, best of 3:
89.7 µs per loop

In [40]: timeit sum(mul(*t) for t in itertools.combinations(xlist, 2))
1000 loops, best of 3:
165 µs per loop

In [41]: %%timeit                                        
x = array(arr)
(x.sum()**2 - (x**2).sum()) / 2
   ....: 
100000 loops, best of 3:
 10.9 µs per loop

In [42]: timeit np.triu(np.outer(x, x), k=1).sum()
10000 loops, best of 3:
48.1 µs per loop
In [59]: %%timeit
....: xarr = np.array(xList)
....: N = xarr.size
....: range1 = np.arange(N)
....: mask = range1[:,None] < range1
....: out = ((mask*xarr)*xarr[:,None]).sum()
10000 loops, best of 3: 30.4 µs per loop

所有列表/数组都有50个元素。

从user2357112窃取逻辑并在sum python的普通列表中使用它非常有效:

In [63]: timeit result = (sum(xList)**2 - sum(x ** 2 for x in xList)) / 2
100000 loops, best of 3: 
4.63 µs per loop

但是对于大型阵列,numpy解决方案仍然要快得多。

答案 2 :(得分:6)

以这种方式:

In [14]: x = [9, 13, 10, 5, 3]

In [15]: np.triu(np.outer(x, x), k=1).sum()
Out[15]: 608

但我会使用@ user2357112的答案。

答案 3 :(得分:4)

看起来你想要获得该列表中两个元素(对)的每个组合,计算每对的乘积,并总结这些产品:

import itertools
import operator

sum(operator.mul(*t) for t in itertools.combinations(xlist, 2))

这样做的单行:

f = @(x) x^2
syms a
df = diff(f(a)) = 2*a
numeric_value1 = f(3) = 9.0
numeric_value2 = subs(df,3) = 6.0

答案 4 :(得分:1)

一种方法 -

xarr = np.array(xList)

N = xarr.size
range1 = np.arange(N)

R,C = np.where(range1[:,None] < range1)
out = (xarr[R]*xarr[C]).sum()

另一个 -

matplotlib.style.use('ggplot')

答案 5 :(得分:1)

如果您有兴趣手动执行此操作(没有stdlib的帮助):

def combinations(L):
    for i,elem in enumerate(L):
        for e in L[i+1:]:
            yield (elem, e)

def main(xlist):
    answer = 0
    for a,b in combinations(xlist):
        answer += a*b
    return answer
相关问题