I want to find out the sum of products of couples in a list. For example a list is given [1, 2, 3, 4]
. What I want to get is answer = 1*2 + 1*3 + 1*4 + 2*3 + 2*4 + 3*4
.
I do it using brute-force, it gives me the time-out error for very large lists. I want an efficient way to do this. Kindly tell me, how can I do this?
Here is my code, this is working but i need more efficient one:
def proSum(list):
count = 0
for i in range(len(list)- 1):
for j in range(i + 1, len(list)):
count += list[i] * list[j]
return count
Here it is:
In [1]: def prodsum(xs):
...: return (sum(xs)**2 - sum(x*x for x in xs)) / 2
...:
In [2]: prodsum([1, 2, 3, 4]) == 1*2 + 1*3 + 1*4 + 2*3 + 2*4 + 3*4
Out[2]: True
Let xs = a1, a2, .., an
, then
(a1+a2+...+an)^2 = 2(a1a2+a1a3+...+an-1an) + (a1^2+...+an^2)
So we have
a1a2+...+an-1an = {(a1+a2+...+an)^2 - (a1^2+...+an^2)}/2
Compare the performance of @georg's method and mine
The result and the test codes as following(The less time used is better):
In [1]: import timeit
In [2]: import matplotlib.pyplot as plt
In [3]: def eastsunMethod(xs):
...: return (sum(xs)**2 - sum(x*x for x in xs)) / 2
...:
In [4]: def georgMethod(given):
...: sum = 0
...: res = 0
...: cur = len(given) - 1
...:
...: while cur >= 0:
...: res += given[cur] * sum
...: sum += given[cur]
...: cur -= 1
...: return res
...:
In [5]: sizes = range(24)
In [6]: esTimes, ggTimes = [], []
In [7]: for s in sizes:
...: t1 = timeit.Timer('eastsunMethod(xs)', 'from __main__ import eastsunMethod;xs=range(2**%d)' % s)
...: t2 = timeit.Timer('georgMethod(xs)', 'from __main__ import georgMethod;xs=range(2**%d)' % s)
...: esTimes.append(t1.timeit(8))
...: ggTimes.append(t2.timeit(8))
In [8]: fig, ax = plt.subplots(figsize=(18, 6));lines = ax.plot(sizes, esTimes, 'r', sizes, ggTimes);ax.legend(lines, ['Eastsun', 'georg'], loc='center');ax.set_xlabel('size');ax.set_ylabel('time');ax.set_xlim([0, 23])
Use itertools.combinations
to generate unique pairs:
# gives [(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
unique_pairs = list(itertools.combinations([1, 2, 3, 4], 2))
Then use a list comprehension to get the product of each pair:
products = [x*y for x, y in unique_pairs] # => [2, 3, 4, 6, 8, 12]
Then use sum
to add up your products:
answer = sum(products) # => 35
This can be all wrapped up in a one-liner like so:
answer = sum(x*y for x,y in itertools.combinations([1, 2, 3, 4], 2))
In making it a one-liner the result of combinations
is used without casting to a list
. Also, the brackets around the list comprehension are discarded, transforming it generator expression .
Note : Eastsun's answer and georg's answer use much better algorithms and will easily outpreform my answer for large lists.
Note : actually @Eastsun's answer is better.
Here's another, more "algorithmical" way to deal with that. Observe that given
a 0 , a 1 , ..., a n
the desired sum is (due to the distributive law)
a 0 (a 1 + a 2 + ... + a n ) + a 1 (a 2 + a 3 + ... + a n ) + ... + a n-2 (a n-1 + a n ) + a n-1 a n
which leads to the following algorithm:
sum
be 0 and current
be the last element sum
and current
and add to the result current
to sum
current
be the previous of current
In python:
sum = 0
res = 0
cur = len(given) - 1
while cur >= 0:
res += given[cur] * sum
sum += given[cur]
cur -= 1
print res
With no external library, you can use map
and lambda
to calculate *
pairwise, and then sum
everything up
l=[1, 2, 3, 4]
sum(map(lambda x,y:x*y, l, l[1:]+[l[0]]))
But since you are dealing with big data, I suggest you use numpy.
import numpy as np
l = np.array([1, 2, 3, 4])
print sum(l*np.roll(l, 1))
# 24
EDIT: to keep up with the updated question of OP
import numpy as np
l = [1, 2, 3, 4]
sums = 0
while l:
sums+=sum(l.pop(0)*np.array(l))
print sums
#35
So what it does is taking out the first element of list and *
with the rest. Repeating until there is nothing to take out from the list.
def sumOfProductsOfCouples(l):返回sum(l [i-1] * l [i],代表inumerate(l)中的i,n)
from itertools import combinations
l=[1, 2, 3, 4]
cnt=0
for x in combinations(l,2):
cnt+=x[0]*x[1]
print (cnt)
Output;
>>>
35
>>>
combinations()
will give your pairs like you want. Then do your calculates.
Debug it like ;
l=[1, 2, 3, 4]
for x in combinations(l,2):
print (x)
>>>
(1, 2)
(1, 3)
(1, 4)
(2, 3)
(2, 4)
(3, 4)
>>>
See that your pairs are here. Actually you will find the sum of this combinations pairs.
Use the permutations
method from the itertools
module:
from itertools import *
p = permutations([1, 2, 3, 4], 2) # generate permutations of two
p = [frozenset(sorted(i)) for i in p] # sort items and cast
p = [list(i) for i in set(p)] # remove duplicates, back to lists
total = sum([i[0] * i[1] for i in p]) # 35 your final answer
you can use map, sum functions.
>>> a = [1, 2, 3, 4]
>>> sum(map(sum, [map(lambda e: e*k, l) for k, l in zip(a, (a[start:] for start, _ in enumerate(a, start=1) if start < len(a)))]))
35
Dividing above expression in parts,
>>> a = [1, 2, 3, 4]
>>> c = (a[start:] for start, _ in enumerate(a, start=1) if start < len(a))
>>> sum(map(sum, [map(lambda e: e*k, l) for k, l in zip(a, c)]))
35
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.